swift - 如何压制 "result not used"警告

标签 swift swift3 xcode8

在 Swift2.2 中,我对 Optional 进行了扩展,如下所示:

extension Optional {
    func ifNotNil<T>(_ closure:(Wrapped) -> T) -> T? {
        switch self {
        case .some (let wrapped):
            return closure(wrapped)
        case .none:
            return nil
        }
    }
}

它允许这样的代码

anImageView.image = self.something.ifNotNil { self.getImageFor($0) }

但有时候,我并不关心结果:

myBSON["key"].string.ifNotNil {
    print($0}
}

在 Swift2.2 中,它就像一个魅力。但是启动新的 XCode8 Beta 并转换为 Swift3,我在执行第二种类型的任何地方都会收到警告。就好像有一个隐式的 @warn_unused_result。这只是一个早期的测试版错误吗?或者我不能再在 Swift3 中做的事情?或者我需要在 Swift3 中新修复的东西?

最佳答案

您可以使用以下方法丢弃结果:

_ = myBSON["key"].string.ifNotNil {
    print($0}
}

或者将您的方法标记为不警告未使用的结果:

extension Optional {

    @discardableResult func ifNotNil<T>(_ closure:(Wrapped) -> T) -> T? {
        switch self {
        case .some (let wrapped):
            return closure(wrapped)
        case .none:
            return nil
        }
    }
}

引用:SE-0047

关于swift - 如何压制 "result not used"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37819965/

相关文章:

c - 带有循环的 Swift 3.1 模式

javascript - Swift React Native 回调模块

swift - 使用 UIImagePicker 选取图像后重新加载 UICollectionView 的正确时机和位置

ios - 从 application(.... launchOptions : [NSObject: AnyObject]? ) 处的 launchOptions 获取值

ios - UITableViewRowAction 与 UISwipeActionsConfiguration

Swift 3 不正确的字符串插值与隐式展开的 Optionals

xcode - 创建音频波可擦洗时间线。 swift 3 MacOS

ios - Xcode 8.3.3 "No accounts with iTunes Connect access"

ios - 测试在 xcode 8 TEST_HOST 错误下停止工作

ios - View 的 UIPageViewController 框架在 iOS 上是不可预测的