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
446 views
in Technique[技术] by (71.8m points)

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

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

I have a dictionary called opts which is declared as <String, AnyObject>

I have this code:

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

and on the lines case "abc" and case "def" I get the following error:

Type 'String' does not conform to protocol 'IntervalType'

Can someone explain to me what I am doing wrong?

question from:https://stackoverflow.com/questions/26865132/strings-in-switch-statements-string-does-not-conform-to-protocol-intervaltyp

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

1 Answer

0 votes
by (71.8m points)

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


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

...