2

Start with the claim that Swift makes that strings are 'mutable', Are Swift "mutable" strings really mutable, or are they just like Java strings?, but proceeding with a generally-accepted (and non-Swift) definition of mutability - ie. strictly value immutability, without consideration of bindings

Is it possible to actually mutate a String value such that this prints 'true'?

var str = "Mutate me!"

let a1 = (unsafeAddressOf(str))
// some 'mutating operation'
let a2 = (unsafeAddressOf(str))

print(a1 == a2)

I am not interested in 'structure types' or delayed copy semantics. This question is about if a string value can be modified, from within Swift - although it would be also be interesting to see if such could be mutated by other .. devious means. (If not it is hogwash to even bother discussing value vs reference types instead of pure mutability considerations.)

I am aware of "mutating" methods but disagree with those as 'mutating' the string value. In the example above, let should be substitutable in the final program. If let cannot be substituted; or the object can otherwise not be proven to be the same, then mutability has not been shown.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • @EricD. Yes, I've read through it. I am trying 'desperately' to counter my belief that Swift documentation is a confusing mixture of terms, at best - and to, hopefully one way or another, be [able to better argue (or concede) against string mutability *independent* of being a value type or having special copy semantics](http://stackoverflow.com/a/32626538/2864740). – user2864740 Sep 17 '15 at 18:45
  • 4
    Note that `unsafeAddressOf()` takes an `AnyObject` parameter, i.e. an instance of a *class*, but `String` is a struct. So what you get is not the address of the struct, but `(unsafeAddressOf(str as NSString))`, due to automatic bridging. I *think* you can get the real address with `withUnsafePointer(&str) { print($0) }`, and that does not change with the string mutation. – Martin R Sep 17 '15 at 19:00
  • @MartinR Good point about the unsafeAddressOf (it was explored more in http://stackoverflow.com/questions/32638879/swift-strings-and-memory-addresses) and the .. magic it does. – user2864740 Sep 17 '15 at 20:56

0 Answers0