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

前端 未结 4 521
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 12:39

    Arrays, dictionaries etc. in Objective-C are often mutable. That means when I pass an array to another method, and then that array is modified behind the back of the other method, surprising (to put it gently) behaviour will happen.

    By making arrays, dictionaries etc. value types, this surprising behaviour is avoided. When you receive a Swift array, you know that nobody is going to modify it behind your back. Objects that can be modified behind your back are a major source for problems.

    In reality, the Swift compiler tries to avoid unnecessary copying whenever possible. So even if it says that an array is officially copied, it doesn't mean that it is really copied.

提交回复
热议问题