Conflicting definition of Swift struct and array

后端 未结 6 1031
孤街浪徒
孤街浪徒 2021-02-01 09:56

In Swift Programming Language, it says:

  1. “all of the basic types in Swift—integers, floating-point numbers, Booleans, strings, arrays and dictio

6条回答
  •  后悔当初
    2021-02-01 10:49

    Array are special cases. They are value types with a special behavior.

    At the page where you found the point 3) there are enough information to understand why:

    The assignment and copy behavior for Swift’s Array type is more complex than for its Dictionary type. Array provides C-like performance when you work with an array’s contents and copies an array’s contents only when copying is necessary

    and, immediately after you statement:

    Instead, both arrays share the same sequence of element values. When you modify an element value through one array, the result is observable through the other.

    For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array.

    So, reading these points we understand that:

    • array are struct but with a special behavior, the mainly reason is to conserve C-like performance.
    • the copy is made only when the length of the copied array is changed

    Last thing: remember that, when an array is copied, only value types (structures, enumerations, primitive types) are copied. Objects are not copied, only their references (pointers) are copied

提交回复
热议问题