解决关于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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值