gpt4 book ai didi

ios - 如何在数组中的每 3 个对象之后添加数组中的对象?

转载 作者:行者123 更新时间:2023-11-28 09:35:19 24 4
gpt4 key购买 nike

我有一个从 0 到 100 的数组。

let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"...."100"]

现在,我想在数组中的每 3 个对象后添加“-”。

所以输出应该是这样的

array = ["0", "1", "2","-","3", "4", "5","-", "6", "7", "8", "-","9"...."100"]

那么,我该如何实现呢?

如果我有模型数组而不是字符串数组呢?

   struct SubCategory { 
var title: String = ""
var subTitle: String = ""
}

let array = [SubCategory]()

最佳答案

let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

extension Array {
func chunks(of size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
let n = Swift.min(size, count - $0)
return Array(self[$0 ..< $0 + n])
}
}
}

let joined = Array(array.chunks(of: 3).joined(separator: ["-"]))

关于ios - 如何在数组中的每 3 个对象之后添加数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52233606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com