why string, array and dictionary in Swift changed to value type

前端 未结 4 520
伪装坚强ぢ
伪装坚强ぢ 2021-02-02 11:54

In Objc string, array and dictionary are all reference types, while in Swift they are all value types.

  1. I want to figure out what\'s the reason behind the scenes

4条回答
  •  攒了一身酷
    2021-02-02 12:35

    I do not know, whether this is the real idea behind it, but have a historical view on it:

    At the beginning, an array copy behaved by reference, when you changed an item in it. It behaved by value, when you changed the length of the array. They did it for performance reasons (less array copy). But of course this was, eh, how can I express that politly, eh, difficult with Swift at all, eh, let's call it a "do not care about a good structure if you can win some performance, you probably never need" approach. Some called that copy-on-write, what is not much more intelligent, because COW is transparent, while that behavior was not transparent. Typical Swift wording: Use a buzzword, use it the way, it fits to Swift, don't care about correctness.

    Later on arrays got a complete by copy behavior, what is less confusing. (You remember, Swift was for readability. Obviously in Swift's concept, readability means "less characters to read", but does not mean "better understandable". Typical Swift wording: Use a buzzword, use it the way, it fits to Swift, don't care about correctness. Did I already mention that?)

    So, I guess it is still performance plus understandable behavior probably leading to less performance. (You will better know when a copy is needed in your code and you can still do that and you get a 0-operation from Cocoa, if the source array is immutable.) Of course, they could say: "Okay, by value was a mistake, we changed that." But they will never say.

    However, now arrays in Swift behave consistently. A big progress in Swift! Maybe you can call it a programming language one sunny day.

提交回复
热议问题