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 } 

1 Answer 1

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 } 
Sign up to request clarification or add additional context in comments.

4 Comments

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
Thanks for the edit @zombie. Now I have the Cranberries' song in my head, in my head ...
let case seems to be cleaner and saves me also from declaring "default" case! Thank you! :)
Hey! I've posted another question related to Swift-compile-issues. Just in case it interests you: stackoverflow.com/questions/56814387/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.