【发布时间】:2015-09-17 09:02:09
【问题描述】:
我先写了 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 的可变字符串时,更改也会反映在 Dictionary 中..
但后来我在 Swift 中尝试了相同的方法
var stringValue:String?
stringValue = "Hello"
var dict:Dictionary = ["name":stringValue!]
println(dict)
stringValue! += " World"
stringValue!.extend(" !!!!")
println(dict)
我的问题是
- 为什么改变的值没有反映在像这样的数据结构中 字典。
- 在 Swift 中添加任何键值是否真的会保留该值或其 参考,如果它保持像objective-C这样的参考,那么我的错误是什么?
【问题讨论】:
标签: objective-c swift reference nsdictionary swift-playground