[swift-evolution] Constant generic properties in mutable contexts

Maximilian H├╝nenberger m.huenenberger at me.com
Sat Jan 30 09:27:51 CST 2016


Hi all,

If you have an Array which is declared as mutable variable all contents are implicitly mutable. This is unfortunate especially in case of value types.

Consider this code example:

    struct Person { var name: String }

    var array = [Person(name: "Smith")]
    // all persons are implicitly mutable
    array[0].name = "Sam"


So I propose a language feature which addresses this issue:

    var array: [let Person] = [Person(name: "Smith")]
    // all persons are immutable
    array[0].name = "Sam" // error

    // but still allowing to add and remove persons
    array[0] = Person(name: "Sam")


For clarification: The semantics are the same as if you've wrapped the struct in a class with a "let" property:

    class ConstantWrapper<T> {
        let value: T
        init(_ value: T) { self.value = value }
    }

    var array = [ConstantWrapper(Person(name: "Smith"))]
    // all persons are "indirect" immutable
    array[0].value.name = "Sam" // error


This model would allow for more immutability in mutable contexts which ultimately leads to less bugs.


##Possible Extensions:

We could also allow a "var" declaration:

    let array: [var Person] = ...

The array models a fixed length array which is highly suggested by some people but you cannot assign a new "Person" to a specific index which is unfortunate. Although this could be solved by tweaking the current model.


Best regards
- Maximilian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160130/a68d0464/attachment.html>


More information about the swift-evolution mailing list