Swift:检查编译器是否支持条件符合



with xcode 9.3 Swift编译器引入了条件符合,使我们可以比较两个选项。

我们正在使用用于支持Swift 3.2和Swift 4.0的库,以及我们必须为字典定义以下比较器的位置:

fileprivate func ==(lhs:[String: NSObject]?, rhs: [String:NSObject]?) -> Bool {
    var match = true
    if let lhs = lhs {
        if let rhs = rhs {
            match = lhs == rhs
        } else {
            match = false
       }
    }
    return match
}

在Swift 3.3和Swift 4.1中,此比较器不再有效,并在线上导致无限循环

match = lhs == rhs

匹配器现在自称为何处。它是一个库,因此我们不能强迫客户使用最新的Xcode版本。

有没有办法检查编译器是否支持条件符合?

较新的Swift版本为字典提供了内置的==操作员以及选项,并且还为可选类型提供了对非选择类型的强制(请参见下面的注释(。

因此,我认为最简单的版本是简单地播放较新的Swift版本的整个== func:

#if !swift(>=3.3)  // check the correct version, I'm not sure about 3.3 or newer
func ==(lhs:[String:Int]?, rhs: [String:Int]?) -> Bool  {
    print ("check same (lhs) == (rhs)")
    var match = true
    if let lhs = lhs {
        if let rhs = rhs {
            match = lhs == rhs
        } else {
            match = false
        }
    }
    return match
}
#endif

var a:[String:NSObject]? = ["a":"c" as NSObject]
var b:[String:NSObject]? = ["a":"c" as NSString]
print (a == b)

备注:

问题在于,在当前的Swift版本中,期望Optional s的函数也可以通过相应的非选项参数调用,如下所示:

func consumesOptional(value: Int?) -> Int {
    print ("consuming (String(describing: value))")
    return value!
}
let x: Int = 1
let y = consumesOptional(value: x)
print(y)    // "consuming Optional(1)"

因此,如果您创建一个可选参数的func ==,然后(在您的if let级联调用==中,带有非可选类型,这将导致递归,如下注释中正确说明。

有关更多详细信息,请参见SE-0121

最新更新