在Swift中的if语句中使用多个let-as [英] Using multiple let-as within a if-statement in Swift
问题描述
我从字典中解开两个值,在使用它们之前,我必须将它们转换为正确的类型。这就是我想出的:
I'm unwrapping two values from a dictionary and before using them I have to cast them and test for the right type. This is what I came up with:
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
}
}
但是如果让查询合二为一,我想打包两个。所以它会是这样的:
But I would like to pack the two if let queries into one. So that it would something like that:
if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
// do stuff here
}
这句法不起作用,所以我想知道是否有一种美妙的方式来做到这一点。
That syntax is not working, so I was wondering if there was a beautiful way to do that.
推荐答案
Swift 3更新:
Update for Swift 3:
以下内容适用于Swift 3:
The following will work in Swift 3:
if let latitudeDouble = latitude as? Double, let longitudeDouble = longitude as? Double {
// latitudeDouble and longitudeDouble are non-optional in here
}
请务必记住,如果其中一个尝试的可选绑定失败,则不会执行 if-let
块内的代码。
Just be sure to remember that if one of the attempted optional bindings fail, the code inside the if-let
block won't be executed.
注意:这些子句不一定都是'let'子句,你可以用逗号分隔任何一系列的布尔检查。
Note: the clauses don't all have to be 'let' clauses, you can have any series of boolean checks separated by commas.
例如:
if let latitudeDouble = latitude as? Double, importantThing == true {
// latitudeDouble is non-optional in here and importantThing is true
}
Swift 1.2:
Swift 1.2:
Apple可能已经阅读了您的问题,因为您的希望 - 为了在Swift 1.2中正确编译代码(今天测试版):
Apple may have read your question, because your hoped-for code compiles properly in Swift 1.2 (in beta today):
if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
// do stuff here
}
Swift 1.1及更早版本:
Swift 1.1 and earlier:
这是个好消息 - 你完全可以做到这一点。关于两个值的元组的switch语句可以使用模式匹配将它们同时转换为 Double
:
Here's the good news - you can totally do this. A switch statement on a tuple of your two values can use pattern-matching to cast both of them to Double
at the same time:
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")
}
更新:此版本的代码现在可以正常运行。
Update: This version of the code now works properly.
这篇关于在Swift中的if语句中使用多个let-as的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!