实例引用在Swift中真的有效吗? [英] Do instance references really work in Swift?

查看:97
本文介绍了实例引用在Swift中真的有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先编写了Objective-C代码

I wrote the Objective-C code first

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的Mutable字符串时,更改也将反映在Dictionary中.

Means when I append a string to a Mutable string which is actually referred into a MutableDictionary, the change is getting reflected in Dictionary too..

但是后来我在Swift中尝试了相同的方法

But then I tried something same in 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

我的问题是

  • 为什么更改的值未反映在像这样的数据结构中 字典.
  • 在Swift中是否添加任何键值确实会保留该值或其值 参考,如果保持像Objective-C这样的参考,那么我的错误是什么?
  • Why the value that changed is not reflecting in a data structure like Dictionary.
  • Does in Swift adding any key value really keeps the value or its reference, if it's keeping the reference like objective-C then here what is my mistake?

推荐答案

引用类型

不同的行为取决于在Objective-C代码中使用NSMutableStringclass的事实. 这意味着aMutDictaStrValue是对NSMutableString类型的同一对象的引用.因此,您可以使用aMutDict来查看使用aStrValue应用的更改.

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.

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

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.

以下示例清楚地描述了value type行为:

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"

希望这会有所帮助.

这篇关于实例引用在Swift中真的有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆