Mru*_*rug 5 reference objective-c nsdictionary swift swift-playground
我首先编写了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);
Run Code Online (Sandbox Code Playgroud)
我得到的输出如下
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";
}
Run Code Online (Sandbox Code Playgroud)
意味着当我将一个字符串附加到Mutable字符串(实际上被称为MutableDictionary)时,该更改也会反映在Dictionary中.
但后来我在Swift尝试了同样的东西
var stringValue:String?
stringValue = "Hello"
var dict:Dictionary = ["name":stringValue!]
println(dict)
stringValue! += " World"
stringValue!.extend(" !!!!")
println(dict)
Run Code Online (Sandbox Code Playgroud)
我的问题是
不同的行为取决于您在 Objective-C 代码中使用NSMutableString的class. 这意味着 和aMutDict是aStrValue对同一类型对象的引用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"
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
159 次 |
| 最近记录: |