When to use protocol in Swift

非 Y 不嫁゛ 提交于 2019-12-05 04:06:26

Protocols have more than one use case, but think of it this way:

  • For classes, protocols provide a lightweight inheritance hierarchy separate from the class hierarchy. Given a class Animal and its subclasses Cat, Dog, Bird, and Insect, how would you specify that only Bird and Insect share the fly method?

  • For structs, protocols provide an inheritance hierarchy that would otherwise be missing entirely! A struct has no superstruct. So, given a struct Bird and a struct Insect, how would you specify that they share a fly method?

Now, you could answer that Bird and Insect just happen to have fly methods and that's the end of the story. But that won't do when you need to speak of the set "all types that have a fly method". And you do need to speak of that set when you want the compiler to be able to send the fly method to an object on the grounds that it has a fly method.

The solution is a protocol:

protocol Flier {
    func fly()
}

Now Flier is a type. An instance of any type that conforms to Flier can be used where a Flier is expected, and the compiler will let you tell any Flier to fly, so the problem is solved:

var myFlier : Flier = Bird() // if Bird conforms to Flier
myFlier.fly() // legal
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!