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);
I got the output as follows
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";
}
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..
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
My Questions are
- 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?
In swift, String is a Struct. Structs are not reference types in Swift, thus it's copied when you setting it to a dictionary.
Reference type
The different behaviours depends on the fact that in the Objective-C code you use
NSMutableString
that is aclass
. This means thataMutDict
andaStrValue
are references to the same object of typeNSMutableString
. So the changes you apply usingaStrValue
are visibile byaMutDict
.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:Hope this helps.
Strings in Swift (copy by value) are completely different than string in Objective C (copy by reference).
From Apple' Swift documentation: