What does “case” mean without switch statement in Swift?

后端 未结 2 1570
灰色年华
灰色年华 2021-02-05 18:51

I ran into this code which is part of a Swift implementation of a linked list in the Swift Algorithm Club. Throughout the implementation the author uses case let fo

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 19:09

    Swift 2 took the pattern paradigm from switch/case statements and allowed it to be used in other contexts (if, while and so on).

    So now, rather than just simple comparisons, you can use these pattern matching comparisons in conditionals as well.

    As one example, rather than:

    if (a >= 0) and (a <= 255)
    

    you can instead use:

    if case 0...255 = a
    

    That's a trivial example but it can become much more useful once you realise the rather large number of pattern matching options available to you.

提交回复
热议问题