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

[已解决]swift中初始化二维数组的值

iOS crifan 3682浏览 0评论

之前已经知道了如何初始化一位数组的值了:

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

但是现在遇到了:

想要初始化二维数组的值,写成:

    var contentList:[[String]]
    init(){
        self.contentList = Array<<String>>(count: 20, repeatedValue: [1, 2, 3, 4, 5, 6, 7])

结果报错:

 Non-associative operator is adjacent to operator of same precedence

写成:

        self.contentList = Array<[String]>(count: 20, repeatedValue: [1, 2, 3, 4, 5, 6, 7])

报错:

Cannot invoke initializer for type ‘Array<[String]>’ with an argument list of type ‘(count: Int, repeatedValue: [Int])’

swift two dimension array init with capacity

swift two dimensional array init with capacity

Swift 2D Array Examples

let points: [[Int]] = [[10, 20], [30, 40]]

->此处我不能手写初始化值,否则就累死了。。。

Two-dimensional array in Swift – Stack Overflow

        self.contentList = Array(count: 20, repeatedValue: [“1”, “2”, “3”, “4”, “5”, “6”, “7”])

也是可以的。

或者是:

        self.contentList = Array(count: 20, repeatedValue: Array(count: 7, repeatedValue: “1”))

[总结]

二维数组的初始化,就是:

Array(count:, repeatedValue:) 去嵌套的初始化即可:

        self.contentList = Array(count: 20, repeatedValue: Array(count: 7, repeatedValue: “1”))

或者是:

        self.contentList = Array(count: 20, repeatedValue: [“1”, “2”, “3”, “4”, “5”, “6”, “7”])

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

发表我的评论
取消评论

表情

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

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