使用Swift 3,您可以使用可选的链接,switch语句或可选的模式来解决您的问题。
1.使用 if let
(可选绑定/可选链接)
在斯威夫特编程语言阐明有关可选链接:
可以将多个查询链接在一起,如果链中的任何链接为nil,则整个链都会正常失败。
因此,在最简单的情况下,可以使用以下模式在可选的链接操作中使用多个查询:
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
if let latitude = latitude as? Double, let longitude = longitude as? Double {
print(latitude, longitude)
}
// prints: 2.0 10.0
2.在switch语句中使用元组和值绑定
作为简单可选链的替代方法,当与元组和值绑定一起使用时,switch语句可以提供一种精细的解决方案:
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
switch (latitude, longitude) {
case let (Optional.some(latitude as Double), Optional.some(longitude as Double)):
print(latitude, longitude)
default:
break
}
// prints: 2.0 10.0
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
switch (latitude, longitude) {
case let (latitude as Double, longitude as Double):
print(latitude, longitude)
default:
break
}
// prints: 2.0 10.0
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
switch (latitude as? Double, longitude as? Double) {
case let (.some(latitude), .some(longitude)):
print(latitude, longitude)
default:
break
}
// prints: 2.0 10.0
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
switch (latitude as? Double, longitude as? Double) {
case let (latitude?, longitude?):
print(latitude, longitude)
default:
break
}
// prints: 2.0 10.0
3.将元组与if case
(可选模式)一起使用
if case
(可选模式)提供了一种方便的方式来解开可选枚举的值。您可以将其与元组一起使用,以便对多个查询执行一些可选的链接:
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
if case let (.some(latitude as Double), .some(longitude as Double)) = (latitude, longitude) {
print(latitude, longitude)
}
// prints: 2.0 10.0
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
if case let (latitude as Double, longitude as Double) = (latitude, longitude) {
print(latitude, longitude)
}
// prints: 2.0 10.0
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
if case let (.some(latitude), .some(longitude)) = (latitude as? Double, longitude as? Double) {
print(latitude, longitude)
}
// prints: 2.0 10.0
let dict = ["latitude": 2.0 as AnyObject?, "longitude": 10.0 as AnyObject?]
let latitude = dict["latitude"]
let longitude = dict["longitude"]
if case let (latitude?, longitude?) = (latitude as? Double, longitude as? Double) {
print(latitude, longitude)
}
// prints: 2.0 10.0