Swift Switch访问'case'内的嵌套属性

时间:2019-06-26 13:13:01

标签: swift switch-statement pattern-matching

遵循此代码段。我试图了解是否有可能在Switch语句中访问对象的嵌套属性,而无需在'case'本身内部进行包装(避免不必要的闭包)。 这是一个愚蠢的简单示例。当然,编译器会失败并显示(图像下方的代码段):

enter image description here

class Z {
    var common = 4
}

class A: Z {

}

class B: Z {

}

class C: Z {
    var specific: String? = "%"
}


let unknown = Z()

switch (unknown, unknown.common) {
case (let a as A, 4):
    break

case (let b as B, 4):
    break

case (let c as C, 4), let nonNilSpecific as? String:
    // use nonNilSpecific WITHOUT unwrap it within the case clousre
    break
default: break
}

1 个答案:

答案 0 :(得分:1)

switch的单个情况下使用多个模式时,它们必须绑定所有相同的变量。

Swift看到这一行:

case (let c as C, 4), let nonNilSpecific as? String:

,并认为您正在尝试匹配(let c as C, 4)let nonNilSpecific as? String。这两个选择绑定了不同的变量,因此在案例主体中,不可能知道绑定了哪些变量。

也许您想要这样的东西:

switch (unknown, unknown.common) {
case (let a as A, 4):
    break

case (let b as B, 4):
    break

case (let c as C, 4) where c.specific != nil:
    // force unwrap safe here, no closure needed
    let nonNilSpecific = c.specific!

default: break
}

使用if

let tuple = (unknown, unknown.common)
if case (let a as A, 4) = tuple {
    // use a
} else if case (let b as B, 4) = tuple {
    // use b
} else if case (let c as C, 4) = tuple, let nonNilSpecific = c.specific {
    // use c and nonNilSpecific
} else {
    // default case
}