1

I was reading this question/answers, which basically showed an interesting behaviour in Java and strings, and two questions came up in my mind:

  1. Are Objective-C/Swift String s behave the same? I mean if I have for example two variables which stores the same literal "someString", internally, will they refer to one "someString" object? I didn't find anything about it in the documentation.
  2. If the answer to my previous question is yes, then is it possible to change same string literals the way like in Java?
Community
  • 1
  • 1
Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
  • Do you make any attempt to test question 1? Write some code and see what you get. – rmaddy Sep 17 '15 at 14:16
  • @rmaddy regarding Swift, I did, however, the `MirrorType` ( http://swiftdoc.org/protocol/MirrorType/ ) protocol declares only `{ get }` attributed properties, so even if I get the value, I won't be able to modify it. And in Obj-C the closest I could get was `object_setInstanceVariable`, but I had no idea how the string stored in an `NSString`, so that was a dead end as well. – Dániel Nagy Sep 17 '15 at 14:33

1 Answers1

2
  1. Not all NSString literals (@"string literal") share the same storage due to compilation units.
  2. NSString literals can not be changed in the program code, they are compiled into readonly segments.
  3. NSString variables, that is that are created at runtime, only are shared by assignment.
  4. NSString instances are immutable and can not be changed after creation.
  5. NSMutableString instances can be modified and all variables pointing to such an instance point to the same change.

Swift is slightly different, as @Grimxn points out, Swift String is not a class and immutability is determined by the declaration syntax: let or var.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • It's worth also pointing out (to complete the OP's question) that Swift `String` is not even a class... – Grimxn Sep 17 '15 at 13:21