实例引用在 Swift 中真的有效吗?

2023-12-03

我先写了 Objective-C 代码

NSMutableString *aStrValue = [NSMutableString stringWithString:@"Hello"];
NSMutableDictionary *aMutDict = [NSMutableDictionary dictionary];
[aMutDict setObject:aStrValue forKey:@"name"];

NSLog(@"Before %@",aMutDict);
[aStrValue appendString:@" World"];
NSLog(@"After %@",aMutDict);

我得到的输出如下

2015-09-17 14:27:21.052 ShareIt[4946:129853] Before {
    name = Hello;
}
2015-09-17 14:27:21.057 ShareIt[4946:129853] After {
    name = "Hello World";
}

意味着当我将一个字符串附加到实际上引用到 MutableDictionary 的可变字符串时,更改也会反映在字典中。

但后来我在 Swift 中尝试了同样的东西

var stringValue:String?
stringValue = "Hello"

var dict:Dictionary = ["name":stringValue!]
println(dict)
stringValue! += " World"
stringValue!.extend(" !!!!")
println(dict)

I seen the output in playground like this enter image description here

我的问题是

  • 为什么改变的值没有反映在像这样的数据结构中 字典。
  • 在 Swift 中添加任何键值是否真的保留该值或其 参考,如果它保留像 Objective-C 这样的参考,那么我的错误是什么?

参考类型

不同的行为取决于您在 Objective-C 代码中使用的事实NSMutableString这是一个class。 这意味着aMutDict and aStrValue are 对同一对象的引用类型的NSMutableString。所以您应用的更改使用aStrValue可见aMutDict.

值类型

另一方面,在 Swift 中你正在使用String struct。这是一个值类型。这意味着当您将值从一个变量复制到另一个变量时,使用第一个变量所做的更改对第二个变量不可见。

下面的例子清楚地描述了value type行为:

var word0 = "Hello"
var word1 = word0

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

word0 // "Hello world"
word1 // "Hello"

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

实例引用在 Swift 中真的有效吗? 的相关文章

随机推荐