在Java中,我们可以简单地填充数组
String[] strings = new String[10];
java.util.Arrays.fill(strings, "hello");
// Re-fill the array with "bye" value.
java.util.Arrays.fill(strings, "bye");
但是,我们如何在 Swift 中执行类似的操作?我能得到的最接近的是
var strings = [String](repeating: "hello", count: 10)
// Re-fill the array with "bye" value.
for index in strings.indices {
strings[index] = "bye"
}
我希望避免以下内容,因为它会创建另一个新的数组实例。
var strings = [String](repeating: "hello", count: 10)
strings = [String](repeating: "bye", count: 10)
有没有办法用新值重新填充数组,而不使用 for 循环?
Swift 默认不提供这样的功能,但 Swift 是一种很好的可扩展语言。
最接近的函数是replaceSubrange(_:with:)
这样你就可以写一个扩展Array
extension Array {
mutating func fill(withValue value: Element) {
replaceSubrange(startIndex..., with: [Element](repeating: value, count: count))
}
}
并使用它
var strings = [String](repeating: "hello", count: 10)
strings.fill(withValue: "bye")
避免循环的努力只是语法糖。几乎所有这些函数都在后台使用循环。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句