1

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
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Roi Mulia
  • 5,626
  • 11
  • 54
  • 105

1 Answers1

3

When you use multiple patterns in a single case of a switch, they must bind all of the same variables.

Swift sees this line:

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

and thinks you're trying to match either (let c as C, 4) or let nonNilSpecific as? String. Those two choices bind different variables, so in the case body it is impossible to know which variables have been bound.

Perhaps you wanted something like this:

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
}

Use an 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
}
zombie
  • 5,069
  • 3
  • 25
  • 54
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Thank you for your reply! It does possible, but I'm trying to come up with a solution which is synchronized, meaning that in a single liner I access the value within the level of the case. But for now doesn't seem possible, at least not with Switch... Let's wait a bit, maybe someone will come up with some black magic lol – Roi Mulia Jun 26 '19 at 13:36
  • 1
    Thanks for the edit @zombie. Now I have the [Cranberries' song](https://www.youtube.com/watch?v=6Ejga4kJUts) in my head, in my head ... – vacawama Jun 26 '19 at 14:32
  • let case seems to be cleaner and saves me also from declaring "default" case! Thank you! :) – Roi Mulia Jun 26 '19 at 14:48
  • Hey! I've posted another question related to Swift-compile-issues. Just in case it interests you: https://stackoverflow.com/questions/56814387/swift-conform-to-protocol-subclass – Roi Mulia Jun 29 '19 at 01:07