最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift中数组批量初始化值

iOS crifan 2950浏览 0评论

swift中需要批量初始化某个数组的值

原先是循环初始化的:

        var itemSizeColumnList = [CGSize]()
        let eachItemSize = CGSize(width: ScreenWidth/CGFloat(collectionViewLayout.numberOfColumns), height: 30)
        for _ in (1…collectionViewLayout.numberOfColumns) {
            itemSizeColumnList.append(eachItemSize)
        }

swift array batch init

swift array init with capacity

Array with capacity in Swift – Stack Overflow

Swift init Array with capacity – Stack Overflow

swift – How to create a fixed-size array of objects – Stack Overflow

Array should have init(capacity: Int) | Apple Developer Forums

        let eachItemSize = CGSize(width: ScreenWidth/CGFloat(collectionViewLayout.numberOfColumns), height: 30)
//        var itemSizeColumnList = [CGSize]()
//        for _ in (1…collectionViewLayout.numberOfColumns) {
//            itemSizeColumnList.append(eachItemSize)
//        }
        let itemSizeColumnList = Array<CGSize>(count: collectionViewLayout.numberOfColumns, repeatedValue: eachItemSize)

即可。

[总结]

批量初始化数组,可以写成:

let batchInitedArray = Array<SomeType>(count: ArrayCount, repeatedValue: initValue)

比如:

let IntArray10 = Array<SomeType>(count: 10, repeatedValue: 0)

转载请注明:在路上 » [已解决]swift中数组批量初始化值

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.178 seconds, using 22.08MB memory