mercredi 26 juin 2019

Swift Switch access nested properties within 'case'

Following this code snippet. I'm trying to understand if it's possible to access nested properties of the object within Switch statement, without the need to unwrap properties inside the 'case' itself (avoid unneeded closures). Here's a stupid-simple example. of course, the compilers fail with (code snippet below image):

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
}

Aucun commentaire:

Enregistrer un commentaire