Swift @autoclosure 在 v1.2 中破坏了枚举案例的兼容性 [英] Swift @autoclosure broke compatibility in v1.2 for enum cases

查看:30
本文介绍了Swift @autoclosure 在 v1.2 中破坏了枚举案例的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将 Xcode 更新到 6.3,以前在 Xcode 6.2 中编译的 Swift 代码现在无法编译.

I just update Xcode to 6.3 and the Swift code that used to compile in Xcode 6.2 is not compiling now.

import Foundation

public enum Result<T> {
    case Success(@autoclosure() -> T)
    case Failure(NSError)
    case Cancelled

    public init(_ value: T) {
        self = .Success(value)
    }

    public init(_ error: NSError) {
        self = .Failure(error)
    }

    public init() {
        self = .Cancelled
    }

    public var failed: Bool {
        switch self {
        case .Failure(let error):
            return true

        default:
            return false
        }
    }

    public var error: NSError? {
        switch self {
        case .Failure(let error):
            return error

        default:
            return nil
        }
    }

    public var value: T? {
        switch self {
        case .Success(let value):
            return value()

        default:
            return nil
        }
    }
}

这一行:case Success(@autoclosure() -> T)

产生错误:'autoclosure' 属性只允许用于参数,不能用于枚举案例

仅仅删除 @autoclosure 并不能解决问题.

Just removing @autoclosure doesn't solve the problem.

推荐答案

正确.这已被删除,明确地防止您提供的情况.Autoclosures 不打算以这种方式使用,Swift 团队有意取消了这样做的能力.在 Result 类型中,这是危险的,因为每次访问时都会重新评估闭包.如果关闭有副作用,这可能会产生非常令人惊讶的影响.即使它只是非平凡的,它也会产生令人惊讶的性能影响.

Correct. This has been removed, explicitly to prevent the case you provide. Autoclosures were not intended to be used this way, and the Swift team intentionally removed the ability to do so. In a Result type, this is dangerous because the closure will be re-evalated every time it is accessed. If there are side-effects in the closure, this can have quite surprising impacts. Even if it's just non-trivial, it can have surprising performance impacts.

这里正确的工具是Box.请参阅 Rob Rix 的 Result这种类型的良好实现.

The correct tool here is Box. See Rob Rix's Result for a good implementation of this type.

这篇关于Swift @autoclosure 在 v1.2 中破坏了枚举案例的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆