Is there a reason that Swift array assignment is inconsistent (neither a reference nor a deep copy)?

后端 未结 10 1129
鱼传尺愫
鱼传尺愫 2020-12-07 08:12

I\'m reading the documentation and I am constantly shaking my head at some of the design decisions of the language. But the thing that really got me puzzled is how arrays a

10条回答
  •  星月不相逢
    2020-12-07 08:32

    The behavior has changed with Xcode 6 beta 3. Arrays are no longer reference types and have a copy-on-write mechanism, meaning as soon as you change an array's content from one or the other variable, the array will be copied and only the one copy will be changed.


    Old answer:

    As others have pointed out, Swift tries to avoid copying arrays if possible, including when changing values for single indexes at a time.

    If you want to be sure that an array variable (!) is unique, i.e. not shared with another variable, you can call the unshare method. This copies the array unless it already only has one reference. Of course you can also call the copy method, which will always make a copy, but unshare is preferred to make sure no other variable holds on to the same array.

    var a = [1, 2, 3]
    var b = a
    b.unshare()
    a[1] = 42
    a               // [1, 42, 3]
    b               // [1, 2, 3]
    

提交回复
热议问题