Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Extending existing types with a protocol

We can declare a type that we haven't declared ourselves, including Swift's own types, to conform to our custom protocol by using an extension:

extension Int: Talkative 
{
func sayHi()
{
print("Hey, I'm \(self)")

if self%2 != 0
{
print("Isn't that odd?")
}
}
}

We can now call the sayHi method on any int:

1.sayHi() 
Note that by using self, we can access the instance's value.

This is something you couldn't do with subclassing--we now have the ability to customize any and all Swift types in any way that we need to, including primitives such as Int and Double.