Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

swift - How case works in if-case

An old C programmer could use some help with Swift.

I don't understanding something about the if-case syntax. E.g.:

if case 20...30 = age {
   print ("in range.")
}

The case 20...30 = age appears to be the conditional test for the if statement. So I was initially confused to see the assignment operator ('=') used instead of a comparison operator ('==').

Ok, I thought to myself, that probably means the case statement is actually a function call that returns a boolean value. The returned value will then satisfy the comparison test in the if statement.

As an experiment, I tried treating the the case statement like a regular conditional test and placed parentheses around it. Swift will happily accept if (x == 5) or if (true). But if (case 20...30 = age) generates an error. So the case statement doesn't seem to behave like function.

I'm just curious to understand what's happening here. Any insight would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The operator is if case, so you can't put parentheses. The syntax and behavior are based on those of the case statement in a Swift switch statement (see my online book if you need details). In a case statement, 20...30 is an interval, used as a pattern, which operates by using contains against the interval. The equals sign is indeed truly confusing, but that was their first attempt at a syntax for expressing what the case statement should be comparing with (i.e. the tag that comes after the switch keyword in a switch statement).

So, if you understand this:

switch age {
case 20...30:
    // do stuff
default:break
}

... then you understand how it is morphed directly into this:

if case 20...30 = age {
   // do stuff
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...