簡體   English   中英

切換語句中的字符串:'String'不符合協議'IntervalType'

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

我在Swift的switch語句中使用字符串時遇到問題。

我有一個名為opts的字典,它被聲明為<String, AnyObject>

我有這個代碼:

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

case "abc"case "def"我收到以下錯誤:

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

有人可以向我解釋我做錯了什么嗎?

在switch語句中使用optional時會顯示此錯誤。 只需打開變量,一切都應該有效。

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

編輯:如果您不想強制打開可選項,可以使用guard 參考: 控制流程:提前退出

根據Swift語言參考

Optional類型是一個枚舉,有兩種情況,None和Some(T),用於表示可能存在或不存在的值。

所以在引擎蓋下,可選類型如下所示:

enum Optional<T> {
  case None
  case Some(T)
}

這意味着您可以在沒有強制解包的情況下前往:

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")
}

這可能更安全,因為如果在opts字典中找不到type ,應用程序不會崩潰。

嘗試使用:

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

我在prepareForSegue()有同樣的錯誤信息,我認為這是相當常見的。 錯誤信息有點不透明,但這里的答案讓我走上正軌。 如果有人遇到這個,你不需要任何類型轉換,只需在switch語句周圍進行條件展開: -

if let segueID = segue.identifier {
    switch segueID {
        case "MySegueIdentifier":
            // prepare for this segue
        default:
            break
    }
}

而不是不安全的力量打開..我發現更容易測試可選案例:

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

(參見案例補充

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM