Do instance references really work in Swift?

前端 未结 3 1577
有刺的猬
有刺的猬 2021-01-19 01:42

I wrote the Objective-C code first

NSMutableString *aStrValue = [NSMutableString stringWithString:@\"Hello\"];
NSMutableDictionary *aMutDict = [NSMutableDict         


        
3条回答
  •  不要未来只要你来
    2021-01-19 02:21

    Reference type

    The different behaviours depends on the fact that in the Objective-C code you use NSMutableString that is a class. This means that aMutDict and aStrValue are references to the same object of type NSMutableString. So the changes you apply using aStrValue are visibile by aMutDict.

    Value type

    On the other hand in Swift you are using the String struct. This is a value type. This means that when you copy the value from one variable to another, the change you do using the first variable are not visible to the second one.

    The following example clearly describes the value type behaviour:

    var word0 = "Hello"
    var word1 = word0
    
    word0 += " world" // this will NOT impact word1
    
    word0 // "Hello world"
    word1 // "Hello"
    

    Hope this helps.

提交回复
热议问题