Abh*_*edi 6 protocols ios swift
我正在浏览这个链接.
但我真的没有得到以下两个代码片段之间的逻辑差异:
1.仅扩展符合协议ErrorPopoverRenderer的UIViewControllers.
protocol ErrorPopoverRenderer {
func presentError(message: String, withArrow shouldShowArrow: Bool, backgroundColor: UIColor, withSize size: CGSize, canDismissByTappingAnywhere canDismiss: Bool)
}
extension UIViewController: ErrorPopoverRenderer { //Make all the UIViewControllers that conform to ErrorPopoverRenderer have a default implementation of presentError
func presentError(message: String, withArrow shouldShowArrow: Bool, backgroundColor: UIColor, withSize size: CGSize, canDismissByTappingAnywhere canDismiss: Bool)
{}
}
Run Code Online (Sandbox Code Playgroud)
2.仅为那些符合它的UIViewControllers扩展协议.
extension ErrorPopoverRenderer where Self: UIViewController {
func presentError() {
}
}
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,任何符合协议的UIViewController子类都将具有默认方法实现,但在UIviewcontroller扩展或协议扩展中.什么是逻辑差异?如果我错了,请纠正我
1
\n\n首先,您ErrorPopoverRenderer使用method 的蓝图presentError(...)创建一个协议。此后,您可以通过实现方法的(强制)蓝图来扩展类UIViewController以符合此协议presentError(...)。
这意味着您可以使用子类UIViewController)的附加协议约束ErrorPopoverRenderer进行子类化。如果UIViewController没有扩展以符合协议 ErrorPopoverRenderer,则您链接的示例中的后续代码将出现编译时错误 ( ... does not comply to protocol ErrorPopoverRenderer)
class KrakenViewController: UIViewController, ErrorPopoverRenderer {\n func failedToEatHuman() {\n //\xe2\x80\xa6\n //Throw error because the Kraken sucks at eating Humans today.\n presentError(ErrorOptions(message: "Oh noes! I didn\'t get to eat the Human!", size: CGSize(width: 1000.0, height: 200.0))) //Woohoo! We can provide whatever parameters we want, or no parameters at all!\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但是,此方法可能存在问题,如您的链接中所示:
\n\n\n\n\n现在,每次我们想要呈现 ErrorView 时,我们都必须实现每个参数。这种情况很糟糕,因为我们无法为协议函数声明提供默认值。
\n
因此该协议ErrorPopoverRenderer不仅仅供UIViewController:s (或其子类)使用,那么上面的解决方案就不是很通用。
2
\n\n如果我们想要更广泛地使用该协议ErrorPopoverRenderer,我们可以在协议扩展 中为可能使用该协议的每个类类型放置特定的蓝图。这确实很巧妙,因为可以为可能符合协议的不同类以不同的方式指定方法蓝图的更具体部分,并且可以使该方法更加简约。ErrorPopoverRendererpresentError()presentError()
我引用这个例子:
\n\n\n\n\n此处使用Self表示只有当且仅当符合者继承自 UIViewController 时,该扩展才会发生。这使我们能够假设ErrorPopoverRenderer 确实是一个 UIViewController,甚至无需扩展 UIViewController。
\n
在这个方法中,由于代码现在知道(我们已经在 1 中知道了)它是一个将调用 的视图控制器presentError(),我们可以将特定的UIViewController东西直接放在蓝图实现中,并且不需要将其作为长消息发送参数列表。
因此,对于这种特定用途,2. 是一种更“通用”的方法,从某种意义上说,我们稍微减少了代码重复(从几个不同的:s 调用presentError()vs )。presentError(... lots of args ...)UIViewController
| 归档时间: |
|
| 查看次数: |
514 次 |
| 最近记录: |