swift协议方法实现_Swift中使协议方法成为可选方法的2种方法

本文翻译自《Better Programming》平台,探讨在Swift中如何使协议方法成为可选,提供了两种不同的实现策略。
摘要由CSDN通过智能技术生成

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协议方法实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值