Andrea Miotto Andrea Miotto - 3 months ago 7
Swift Question

How to instantiate default implementation of Protocol fully defined by Extensions

Would you like to explain me what's wrong in this code? I'm trying to understand the protocols' default implementation

protocol Person {
var name: String {get}
func printName() -> String
}

extension Person {
var name: String {
return "Andrea"
}
}

extension Person {
func printName() -> String {
return "\(name) bye bye"
}
}

struct person: Person {} //correct

person.name // error

person.printName() // error

Answer

You're confusing types and values.

struct person is a new type that adopts the Person protocol.

Now you need to define an instance.

This should be clearer:

protocol PersonProtocol {
    var name: String {get}
    func printName() -> String
}

extension PersonProtocol {
    var name: String {
        return "Andrea"
    }
}

extension PersonProtocol {
    func printName() -> String {
        return "\(name) bye bye"
    }
}

struct ConcretePersonType: PersonProtocol { } // correct

var personInstance = ConcretePersonType()

print(personInstance.name)  // No more error!

personInstance.printName() // No more error!
Comments