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

后端 未结 10 1122
鱼传尺愫
鱼传尺愫 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:18

    What I've found is: The array will be a mutable copy of the referenced one if and only if the operation has the potential to change the array's length. In your last example, f[0..2] indexing with many, the operation has the potential to change its length (it might be that duplicates are not allowed), so it's getting copied.

    var e = [1, 2, 3]
    var f = e
    e[0..2] = [4, 5]
    e // 4,5,3
    f // 1,2,3
    
    
    var e1 = [1, 2, 3]
    var f1 = e1
    
    e1[0] = 4
    e1[1] = 5
    
    e1 //  - 4,5,3
    f1 // - 4,5,3
    

提交回复
热议问题