最新消息:VPS服务器又从fzhost.net换回Linode了,主题仍用朋友推荐的大前端D8

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

iOS crifan 449浏览 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,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
16 queries in 0.212 seconds, using 10.68MB memory