swift协议方法实现
In this article, we’ll learn about two ways to make protocol methods optional. We’ll explore the advantages and disadvantages of each approach.
在本文中,我们将学习使协议方法成为可选方法的两种方法。 我们将探讨每种方法的优缺点。
Without further ado, let’s get started.
事不宜迟,让我们开始吧。
默认实施 (Default Implementation)
The first approach is to create an extension of a protocol and include an empty method of the protocol:
第一种方法是创建协议的扩展并包括该协议的空方法:
This way we make the didDismiss()
method optional. Let’s see what happens when we conform to the PickerViewDelegate
protocol:
这样,我们使didDismiss()
方法成为可选的。 让我们看看当我们遵循PickerViewDelegate
协议时会发生什么:
The compiler doesn’t require us to implement the didDismiss()
method.
编译器不需要我们实现didDismiss()
方法。
优点 (Advantages)
- We can also conform structures to a protocol 我们还可以使结构符合协议
- Default implementation inside the extension is automatically used when we don’t implement the method inside the conforming type 当我们不在符合类型内实现方法时,将自动使用扩展内的默认实现
缺点 (Disadvantages)
In cases when an optional method returns a non-
Void
value, we’ll need to come up with and return some value inside the default implementation在可选方法返回非
Void
值的情况下,我们需要在默认实现内提出并返回一些值
Objective-C“可选”关键字 (Objective-C ‘optional’ Keyword)
We can mark the protocol with the @objc
keyword and the optional method with @objc optional
:
我们可以使用@objc
关键字标记协议,并使用@objc optional
标记可选方法:
This way, we don’t need to create an extension — all we need to do is conform a class to the protocol:
这样,我们不需要创建扩展-我们要做的就是使一个类符合协议:
优点 (Advantages)
- No need to create an extension 无需创建扩展
缺点 (Disadvantages)
Only
NSObject
subclasses can inherit from an@objc
protocol. That means we cannot conform structs or enums to the protocol.只有
NSObject
子类可以从@objc
协议继承。 这意味着我们不能使结构或枚举符合该协议。If we suddenly need to call an optional method, we must include the
?
or!
symbol after the method’s name (if we use force unwrap and the method is not implemented, the app will crash):如果突然需要调用可选方法,则必须包含
?
或!
方法名称后的符号(如果我们使用强制展开并且未实现该方法,则应用程序将崩溃):
Though it may seem the second approach looks neat at first sight, it’s recommended to use the first one, as it allows for more flexibility.
尽管第二种方法乍看起来似乎很整洁,但建议使用第一种,因为它可以提供更大的灵活性。
结语 (Wrapping Up)
Interested in more lesser-known features of Swift? Feel free to check out my other relevant articles:
对Swift鲜为人知的功能感兴趣吗? 随时查看我的其他相关文章:
Thanks for reading!
谢谢阅读!
翻译自: https://medium.com/better-programming/2-ways-to-make-protocol-methods-optional-in-swift-f032836a343b
swift协议方法实现