How do you create an immutable array in Swift?

后端 未结 5 797
臣服心动
臣服心动 2020-11-30 04:16

How do I create an immutable array in Swift?

A superficial reading of the docs would suggest you can just do

let myArray = [1,2,3]

5条回答
  •  失恋的感觉
    2020-11-30 04:37

    IMHO the simplest workaround is simply wrap it in the closure as follows:

    let mutableElements =  [0,1,2,3]
    let reallyImmutable = {[0,1,2,3]}
    println(mutableElements)
    for i in 0..mutableElements.count { mutableElements[i] *= -1 }
    println(mutableElements)    // [0, -1, -2, -3]
    println(reallyImmutable())
    for i in 0..reallyImmutable().count { reallyImmutable()[i] *= -1 }
    println(reallyImmutable())      // [0, 1, 2, 3]
    println(reallyImmutable()[2])   // 2
    let anotherImmutable = { reallyImmutable().map{ $0 * $0 } }
    println(anotherImmutable())     // [0, 1, 4, 9]
    

    You pay extra {} on declaration and () for each access but that also makes your code speak for itself.

    Dan the Mutable Programmer

    P.S. Wrote a wrapper class ImmutableArray.

提交回复
热议问题