在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")
避免循环的努力只是语法上的糖。几乎所有这些函数都在底层使用了循环。