Swift: Failed to assign value to a property of protocol?

后端 未结 1 1271
刺人心
刺人心 2020-12-03 23:12

Class A provides a string value. Class B has two members of A type inside itself, and provide a computed property \"v\" to choose one of them.

class A {
             


        
相关标签:
1条回答
  • 2020-12-03 23:58

    You have to define the protocol as a class protocol:

    protocol ValueProvider : class {
        var value: String {get set}
    }
    

    Then

    var value: String {
        get { return v.value }
        set { v.value = newValue }
    }
    

    compiles and works as expected (i.e. assigns the new value to the object referenced by v1 if v1 != nil, and to the object referenced by v2 otherwise).

    v is a read-only computed property of the type ValueProvider. By defining the protocol as a class protocol the compiler knows that v is a reference type, and therefore its v.value property can be modified even if the reference itself is a constant.

    Your initial code example works because there the v property has the type A which is a reference type.

    And your workaround

    set {
        var tmp = v1 ?? v2
        tmp.value = newValue
    }
    

    works because (read-write) properties of variables can be set in any case (value type or reference type).

    0 讨论(0)
提交回复
热议问题