我正在从字典中解包两个值,在使用它们之前我必须转换它们并测试正确的类型。这是我想出的:
var latitude : AnyObject! = imageDictionary["latitude"]
var longitude : AnyObject! = imageDictionary["longitude"]
if let latitudeDouble = latitude as? Double {
if let longitudeDouble = longitude as? Double {
// do stuff here
}
}
但我想将两个 if let 查询合二为一。所以它会是这样的:
if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
// do stuff here
}
该语法不起作用,所以我想知道是否有一种漂亮的方法可以做到这一点。
最佳答案
Swift 3 更新:
以下将在 Swift 3 中工作:
if let latitudeDouble = latitude as? Double, let longitudeDouble = longitude as? Double {
// latitudeDouble and longitudeDouble are non-optional in here
}
请务必记住,如果尝试的可选绑定(bind)之一失败,则不会执行 if-let
block 中的代码。
注意:子句不一定都是“let”子句,您可以使用逗号分隔的任何一系列 bool 检查。
例如:
if let latitudeDouble = latitude as? Double, importantThing == true {
// latitudeDouble is non-optional in here and importantThing is true
}
Swift 1.2:
Apple 可能已经阅读了您的问题,因为您希望的代码可以在 Swift 1.2(今天处于测试阶段)中正确编译:
if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
// do stuff here
}
Swift 1.1 及更早版本:
好消息是——您完全可以做到这一点。两个值的元组上的 switch 语句可以使用模式匹配将它们同时转换为 Double
:
var latitude: Any! = imageDictionary["latitude"]
var longitude: Any! = imageDictionary["longitude"]
switch (latitude, longitude) {
case let (lat as Double, long as Double):
println("lat: \(lat), long: \(long)")
default:
println("Couldn't understand latitude or longitude as Double")
}
更新:此版本的代码现在可以正常工作。
关于if-statement - 在 Swift 中的 if 语句中使用多个 let-as,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592004/