关于swift的Array repeating 初始化多个对象问题
解决Array repeating初始化只有一个对象
Array repeating的使用
在swift里面系统提供一个一个方法,初始化一个有初始值的指定长度的数组
/// Creates a new array containing the specified number of a single, repeated
/// value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
@inlinable public init(repeating repeatedValue: Element, count: Int)
swift文档已经给我们一个demo了
let fiveZs = Array(repeating: "Z", count: 5)
print(fiveZs)
// Prints "["Z", "Z", "Z", "Z", "Z"]"
有时候我们有个需要,需要初始化多个指定的UIView , 按照官方的
let arr = Array(repeating: UIButton(), count: 5)
我们发现我初始化5个按钮,结果却是5个指向同一个地址的按钮
毫无疑问,你对这个数组进行遍历的时候,可能只有最后一个按钮有作用
Array repeating的替代方案
1. 使用 Range 和 map
let range = 0 ... 4
lazy var buttons = range.map { _ in UIButton() }
lazy var lables = range.map { _ in UILabel() }
2. 使用 Range 和 for (有点智障,没有第一种高级)
var array = [UIView]()
for _ in 0 ..< 5 {
array.append(UIView())
//array += [UIView()] //also works
}
3. 使用 AnyIterator (高级玩家)
let anyIterator = AnyIterator(UIView.init)
let array = Array(anyIterator.prefix(5))
4. 使用struct 实现Sequence 和IteratorProtocol 代理 (骨灰级玩家)
struct ViewSequence: Sequence, IteratorProtocol {
let count: Int
private var index = 0
init(count: Int) {
self.count = count
}
mutating func next() -> UIView? {
guard index < count else { return nil }
defer { index = index.advanced(by: 1) }
return UIView()
}
}
let sequence = ViewSequence(count: 5)
let array = Array(sequence)