Cannot assign to property in protocol - Swift compiler error

后端 未结 3 662
我在风中等你
我在风中等你 2020-12-01 07:10

I\'m banging my head against the wall with the following code in Swift. I\'ve defined a simple protocol:

protocol Nameable {
    var name : String { get set          


        
3条回答
  •  感情败类
    2020-12-01 08:00

    It's because, Nameable being a protocol, Swift doesn't know what kind (flavor) of object your function's incoming Nameable is. It might be a class instance, sure - but it might be a struct instance. And you can't assign to a property of a constant struct, as the following example demonstrates:

    struct NameableStruct : Nameable {
        var name : String = ""
    }
    let ns = NameableStruct(name:"one")
    ns.name = "two" // can't assign
    

    Well, by default, an incoming function parameter is a constant - it is exactly as if you had said let in your function declaration before you said nameable.

    The solution is to make this parameter not be a constant:

    func nameNameable(var nameable: Nameable, name: String ) {
                      ^^^
    

    NOTE Later versions of Swift have abolished the var function parameter notation, so you'd accomplish the same thing by assigning the constant to a variable:

    protocol Nameable {
        var name : String { get set }
    }
    func nameNameable(nameable: Nameable, name: String) {
        var nameable = nameable // can't compile without this line
        nameable.name = name
    }
    

提交回复
热议问题