Reputation:
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
Upvotes: 0
Views: 111
Reputation: 1472
Protocols
are not data types. You are trying to use it as a data type in this line :
struct person: Person {}
Instead, you should use a struct
/enum
/class
that conforms to a protocol
.
In your case, the optimum solution would be to use struct
:
struct PersonStruct: Person {}
let foo = PersonStruct()
print(foo.name)
foo.printName()
Upvotes: 0
Reputation: 8718
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!
Upvotes: 4
Reputation: 6114
You try to use static methods that not exist; make instance of struct instead:
struct Friend: Person {}
let friend = Friend()
print(friend.name)
friend.printName()
Upvotes: 2