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.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...