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

前端 未结 5 990
我在风中等你
我在风中等你 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:29

    According to Swift Language Reference:

    The type Optional is an enumeration with two cases, None and Some(T), which are used to represent values that may or may not be present.

    So under the hood an optional type looks like this:

    enum Optional {
      case None
      case Some(T)
    }
    

    This means that you can go without forced unwrapping:

    switch opts["type"] {
    case .Some("A"):
      println("Type is A")
    case .Some("B"):
      println("Type is B")
    case .None:
      println("Type not found")
    default:
      println("Type is something else")
    }
    

    This may be safer, because the app won't crash if type were not found in opts dictionary.

提交回复
热议问题