ios – “让_ = …”(让下划线相等)在Swift中有用吗?

前端之家收集整理的这篇文章主要介绍了ios – “让_ = …”(让下划线相等)在Swift中有用吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用let _ = …是否有任何目的?

我已经看到了What’s the _ underscore representative of in Swift References?的问题和答案,我知道下划线can be used to represent a variable that isn’t needed.

如果我只需要一个元组的值,就像上面链接中的示例一样,这是有意义的:

let (result,_) = someFunctionThatReturnsATuple()

但是,我最近遇到了this code

do {
    let _ = try DB.run( table.create(ifNotExists: true) {t in
        t.column(teamId,primaryKey: true)
        t.column(city)
        t.column(nickName)
        t.column(abbreviation)
        })

} catch _ {
    // Error throw if table already exists
}

如果我删除let _ =,我不会收到任何编译器警告或错误.在我看来,这样更简单,更易读.

try DB.run( table.create(ifNotExists: true) {t in
    t.column(teamId,primaryKey: true)
    t.column(city)
    t.column(nickName)
    t.column(abbreviation)
    })

代码的作者写了a book and a blog about Swift.我知道作者不是绝对正确的,但它让我想知道是否有我遗漏的东西.

解决方法

如果方法已使用 developer documentation中的warn_unused_result标记,您将收到编译器警告:

Apply this attribute to a method or function declaration to have the compiler emit a warning when the method or function is called without using its result.

You can use this attribute to provide a warning message about incorrect usage of a nonmutating method that has a mutating counterpart.

原文链接:https://www.f2er.com/iOS/332311.html

猜你在找的iOS相关文章