4

解析 Swift 中的 @discardableResult

 2 years ago
source link: https://xie.infoq.cn/article/fef30fd533cdff4278f0a85ff
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

解析 Swift 中的 @discardableResult

SwiftMic
关注
发布于: 2020 年 06 月 15 日

当写 Swift 方法时,你可能经常会遇到这样的场景:

有时候想要忽略方法的返回值,但有时候又需要处理返回值。

@discardableResult 属性可以帮我们消除因方法返回值未被使用而出现的 警告下划线

虽然它是 Swift 中的一个小功能,但最好也了解下。

考虑是否使用 @discardableResult 属性是一件比较重要的事,因为它可以消除这一类的 警告

Result of call to ‘updateName’ is unused

如果整个项目中总是出现这类 警告 的话,也是挺讨厌的。

118b9fc7051b89b94a46dc28a59f9515.png

但是,也并不是说总是加 @discardableResult 属性就是一个明智的选择。上述示例中,最好还是让用户处理下 APIProvider 方法的返回值比较好一些。

enum APIProvder {    static func updateName(_ name: String) -> Result<User, Error> {        // .. Handle API endpoint, example result:        return .success(User(name: name))    }}

如代码所示,返回结果也可能是一个 error ,它会告诉用户出错了。所以,是否需要使用 @discardableResult 属性主要是取决于是否需要处理返回的结果。

上述示例中,如果不使用 @discardableResult 属性的话,需要通过 下划线 才能消除 警告

final class UpdateNameViewController {    func didEnterName(_ name: String) {        /// The underscore makes the warning go away.        _ = APIProvder.updateName(name)    }}

但是,整个项目中过多的 下划线 看起来并不简洁。因此,这种情况下最好还是使用 @discardableResult 关键词。

enum APIProvder {    @discardableResult static func updateName(_ name: String) -> Result<User, Error> {        // .. Handle API endpoint, example result:        return .success(User(name: name))    }}

@discardableResult 属性可能很少被人熟知,但是对于想消除方法返回值未被使用的 警告 来说的话,该属性还是很有用的,只需要在对应方法前添加 @discardableResult 属性即可。但是,还是要考虑是否真的需要忽略该类 警告,因为有些情况下及时处理返回结果可能是一种更好的解决方案。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK