Hacker News new | past | comments | ask | show | jobs | submit login

So strings are mutable? I'm not sure that's a reason to celebrate.



The example does not demonstrate mutability of strings; it is constructing a set of strings and inserting a string element. Only the set is being mutated.

But yes, in Swift, arrays, dictionaries, sets and strings are all mutable. They are also value types, so mutation is a purely local effect.


I think what the example is supposed to demonstrate is that champagne is a type of wine.


Would that not make passing around data expensive? Or are you expected to pass some kind of pointer instead?


Copy-on-write alleviates some of the overhead. Copies are only performed where required to preserve value semantics.


All of these can be both mutable or immutable. And converted as needed

let array = [1, 2, 3] var mutableArray = [4, 5, 6] var anotherMutable = array

Not sure how much optimisation is done under the hood, but Swift compiler loves to complain about mutable structures that are not ever edited.


These are all copy-on-write boxed types with value semantics: the value you pass around is a pointer (with some additional data) and Swift has mechanisms/API which let the implementor copy the backing buffer on mutation if necessary: https://developer.apple.com/documentation/swift/2429905-iskn...


Strings (and arrays and sets and dictionaries) are neither mutable nor immutable in Swift, they're just values. Mutability is a property of where they're stored, not the types themselves. They work just like numbers do in most programming languages: you wouldn't say that Java's `int` is mutable or immutable, it just is. It may be stored in a mutable or immutable location, but the type itself doesn't have that property.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: