Swift 在一个 if 语句中展开多个相互依赖的可选项
Swift unwrap multiple optionals depending on each other in one if statement
我知道你可以像这样使用 if let 语法在一行中解包多个可选值
if let x = optionalX, y = optionalY {
//do something
}
我想要的是在一行中展开多个相互依赖的可选项。目前看起来像这样
if let a = optionalA {
if let ab = a.optionalB {
if let abc = ab.optionalC {
//do something
}
}
}
IMO 这看起来真的很不干净,特别是如果你还想要其他案例,因为你必须将它添加到每个案例中。我想要的看起来像这样,但它不起作用
if let a = optionalA, ab = a.optionalB {
//do something
}
更新
以上代码确实有效!
我在其他地方遇到了一个错误,这使得错误看起来像是在语句中发生的。
你可以这样做:
guard let a = optionalA,
let b = a.optionalB,
let c = b.optionalC
else {
// else implementation
return
}
// do something with constants a, b and c
问题出在 class 声明上,而不是可选的。
classA
应该更像:
classA {
let optionalB : B? = nil
}
您可以 mix conditions and optional unwrapping separated by commas in a single if condition in Swift 3.0(也许是 2.3)。为了让编译器能够区分一个可选的解包,你需要在每个逗号后再次写 let
:
if let a = optionalA,
let ab = a.optionalB {
// Do stuff
}
如果您只想使用 a
(类型 A
)的(可能的)实例内部变量 b
(类型 B
),您可以使用单个可选绑定子句中的可选链接
class A {
var optionalB : B?
}
class B {}
var optionalA : A?
// in case you needn't actually use optionalA, but only its
// possibly non-nil instance member `optionalB`
if let b = optionalA?.optionalB {
//do something with b
}
我知道你可以像这样使用 if let 语法在一行中解包多个可选值
if let x = optionalX, y = optionalY {
//do something
}
我想要的是在一行中展开多个相互依赖的可选项。目前看起来像这样
if let a = optionalA {
if let ab = a.optionalB {
if let abc = ab.optionalC {
//do something
}
}
}
IMO 这看起来真的很不干净,特别是如果你还想要其他案例,因为你必须将它添加到每个案例中。我想要的看起来像这样,但它不起作用
if let a = optionalA, ab = a.optionalB {
//do something
}
更新
以上代码确实有效!
我在其他地方遇到了一个错误,这使得错误看起来像是在语句中发生的。
你可以这样做:
guard let a = optionalA,
let b = a.optionalB,
let c = b.optionalC
else {
// else implementation
return
}
// do something with constants a, b and c
问题出在 class 声明上,而不是可选的。
classA
应该更像:
classA {
let optionalB : B? = nil
}
您可以 mix conditions and optional unwrapping separated by commas in a single if condition in Swift 3.0(也许是 2.3)。为了让编译器能够区分一个可选的解包,你需要在每个逗号后再次写 let
:
if let a = optionalA,
let ab = a.optionalB {
// Do stuff
}
如果您只想使用 a
(类型 A
)的(可能的)实例内部变量 b
(类型 B
),您可以使用单个可选绑定子句中的可选链接
class A {
var optionalB : B?
}
class B {}
var optionalA : A?
// in case you needn't actually use optionalA, but only its
// possibly non-nil instance member `optionalB`
if let b = optionalA?.optionalB {
//do something with b
}