有没有更好的方法来处理 Swift 的嵌套 "if let" "pyramid of doom?"
Is there a better way of coping with Swift's nested "if let" "pyramid of doom?"
有没有比嵌套 if let 语句更好的处理可选属性链的方法?我被建议在检查可选属性时使用 if lets,这是有道理的,因为它在编译时而不是 运行 时处理它们,但它看起来完全疯狂!有没有更好的方法?
这是我最终得到的当前 "pyramid of doom",例如:
( users: [ JSONValue ]? ) in
if let jsonValue: JSONValue = users?[ 0 ]
{
if let json: Dictionary< String, JSONValue > = jsonValue.object
{
if let userIDValue: JSONValue = json[ "id" ]
{
let userID: String = String( Int( userIDValue.double! ) )
println( userID )
}
}
}
Post-脚本
Airspeed Velocity 下面的答案是正确的答案,但您需要 Swift 1.2 才能按照他的建议使用逗号分隔的多个 let,目前只有 XCode 中的 运行s 6.3,处于测试阶段。
正如评论者所说,Swift 1.2 现在有多重语法:
if let jsonValue = users?.first,
json = jsonValue.object,
userIDValue = json[ "id" ],
doubleID = userIDValue.double,
userID = doubleID.map({ String(Int(doubleID))})
{
println( userID )
}
就是说,在这种情况下,您似乎可以通过 1.1 中的可选链接来完成这一切,具体取决于您的对象是什么:
if let userID = users?.first?.object?["id"]?.double.map({String(Int([=11=]))}) {
println(userID)
}
请注意,使用 first
(如果这是一个数组)比 [0]
好得多,因为数组可能为空。并在 double
而不是 !
上映射(如果该值不能翻倍,这将爆炸)。
在 Swift 2 中,我们有 guard
语句。
而不是:
func myFunc(myOptional: Type?) {
if let object = myOptional! {
...
}
}
你可以这样做:
func myFunc(myOptional: Type?) {
guard array.first else { return }
}
从 NSHipster 检查 http://nshipster.com/guard-and-defer/。
Swift-3 的更新:语法已更改:
if let jsonValue = users?.first,
let json = jsonValue.object,
let userIDValue = json[ "id" ],
let doubleID = userIDValue.double,
let userID = doubleID.map({ String(Int(doubleID))})
{
println( userID )
}
有没有比嵌套 if let 语句更好的处理可选属性链的方法?我被建议在检查可选属性时使用 if lets,这是有道理的,因为它在编译时而不是 运行 时处理它们,但它看起来完全疯狂!有没有更好的方法?
这是我最终得到的当前 "pyramid of doom",例如:
( users: [ JSONValue ]? ) in
if let jsonValue: JSONValue = users?[ 0 ]
{
if let json: Dictionary< String, JSONValue > = jsonValue.object
{
if let userIDValue: JSONValue = json[ "id" ]
{
let userID: String = String( Int( userIDValue.double! ) )
println( userID )
}
}
}
Post-脚本
Airspeed Velocity 下面的答案是正确的答案,但您需要 Swift 1.2 才能按照他的建议使用逗号分隔的多个 let,目前只有 XCode 中的 运行s 6.3,处于测试阶段。
正如评论者所说,Swift 1.2 现在有多重语法:
if let jsonValue = users?.first,
json = jsonValue.object,
userIDValue = json[ "id" ],
doubleID = userIDValue.double,
userID = doubleID.map({ String(Int(doubleID))})
{
println( userID )
}
就是说,在这种情况下,您似乎可以通过 1.1 中的可选链接来完成这一切,具体取决于您的对象是什么:
if let userID = users?.first?.object?["id"]?.double.map({String(Int([=11=]))}) {
println(userID)
}
请注意,使用 first
(如果这是一个数组)比 [0]
好得多,因为数组可能为空。并在 double
而不是 !
上映射(如果该值不能翻倍,这将爆炸)。
在 Swift 2 中,我们有 guard
语句。
而不是:
func myFunc(myOptional: Type?) {
if let object = myOptional! {
...
}
}
你可以这样做:
func myFunc(myOptional: Type?) {
guard array.first else { return }
}
从 NSHipster 检查 http://nshipster.com/guard-and-defer/。
Swift-3 的更新:语法已更改:
if let jsonValue = users?.first,
let json = jsonValue.object,
let userIDValue = json[ "id" ],
let doubleID = userIDValue.double,
let userID = doubleID.map({ String(Int(doubleID))})
{
println( userID )
}