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

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

    Note that array semantics and syntax was changed in Xcode beta 3 version (blog post), so the question no longer applies. The following answer applied to beta 2:


    It's for performance reasons. Basically, they try to avoid copying arrays as long as they can (and claim "C-like performance"). To quote the language book:

    For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array. This includes appending, inserting, or removing items, or using a ranged subscript to replace a range of items in the array.

    I agree that this is a bit confusing, but at least there is a clear and simple description of how it works.

    That section also includes information on how to make sure an array is uniquely referenced, how to force-copy arrays, and how to check whether two arrays share storage.

提交回复
热议问题