Strings in Switch Statements: 'String' does not conform to protocol 'IntervalType'

前端 未结 5 941
我在风中等你
我在风中等你 2021-02-05 00:40

I am having problems using strings in switch statements in Swift.

I have a dictionary called opts which is declared as

5条回答
  •  野性不改
    2021-02-05 01:35

    This error is shown when an optional is used in a switch statement. Simply unwrap the variable and everything should work.

    switch opts["type"]! {
      case "abc":
        println("Type is abc")
      case "def":
        println("Type is def")
      default:
        println("Type is something else")
    }
    

    Edit: In case you don't want to do a forced unwrapping of the optional, you can use guard. Reference: Control Flow: Early Exit

提交回复
热议问题