Switch statement in Swift

后端 未结 7 1613
礼貌的吻别
礼貌的吻别 2020-12-01 01:26

I\'m learning syntax of Swift and wonder, why the following code isn\'t working as I expect it to:

for i in 1...100{

    switch (i){
    case 1:
        Int         


        
7条回答
  •  悲&欢浪女
    2020-12-01 01:44

    The industry standard behaviour of switch can lead to bugs similar to "Go to Fail".

    Basically the code doesn't always do exactly what it looks like the code will do when reading over it, which leads to code auditors skipping over critical bugs.

    To counter that, Apple has decided switch statements should not work the same in Swift as the industry standard. In particular:

    • There is an automatic break at the end of every case. It's impossible for more than one case statement to execute.
    • If it's theoretically possible for one of the case statements to be missed, then the code will not compile at all. In swift one of the case statements will always execute, no matter what value is provided. If you provide an enum, every enum value must be handled. If a new value is added to an existing enum the code won't compile until new case statements are added. If you provide a 32 bit integer, you must handle every possible value of a 32 bit int.

提交回复
热议问题