- Mastering macOS Programming
- Stuart Grimshaw
- 150字
- 2021-07-02 22:54:36
Conforming to a protocol
Declaring a type to conform to a protocol is very straightforward:
struct ChattyStruct: Talkative
{
}
At this point, the compiler will point out the fact that your type does not yet conform to the protocol, since it doesn't yet implement the sayHi function, so let's fix that:
struct ChattyStruct: Talkative
{
func sayHi()
{
print("hi")
}
}
Now we can call the sayHi method on any ChattySruct type object:
let anon = ChattyStruct()
anon.sayHi()
Note that we didn't include any default implementation of the required method in the protocol declaration. To do that, we would need to create an extension of the protocol:
extensionTalkative
{
func sayBye(){
print("bye!")
}
}
Now we can call that method, and since ChattyStruct has not provided its own implementation, the default is used, so both these lines of code will print the appropriate text to the console:
anon.sayHi()
anon.sayBye()