2017-02-24 110 views
3

我執行嘗試捕捉枚舉:類型不符合協議CustomStringConvertible

enum processError: Error, CustomStringConvertible { 

     case one 
     var localizedDescription: String{ 
      return "one" 
     } 
     case two 
     var localizedDescription: String { 
      return "two" 
     } 
    } 

但我發現了以下錯誤:

type processError does not conform to protocol CustomStringConvertible

但是,如果我改變變量的名稱在第二種情況下我沒有得到錯誤:

enum processError: Error, CustomStringConvertible { 

    case one 
    var localizedDescription: String{ 
     return "one" 
    } 
    case two 
    var description: String { 
     return "two" 
    } 
} 

我的問題是爲什麼我不能有相同的名稱的變種適用於所有情況?

我真的很感謝你的幫助。

+0

按⌘4,點擊旁邊的錯誤的三角形。你會看到:*協議需要屬性'description' ... *,並且你不能聲明兩次具有相同名稱的變量(*無效的重新聲明... *錯誤) – vadian

+0

可能相關:[如何提供本地化描述和錯誤鍵入Swift?](http://stackoverflow.com/questions/39176196/how-to-provide-a-localized-description-with-an-error-type-in​​-swift)。 –

+0

@ user2924482'枚舉的processError:字符串,錯誤{ 情況一,二 Var描述:字符串{ 回報rawValue } }' –

回答

4

的問題是,CustomStringConvertible協議需要一個屬性:

var description: String 

你需要有description財產或者你會得到它不符合協議的錯誤。

我也建議這種做法:

enum processError: Error, CustomStringConvertible { 
    case one 
    case two 

    var description: String { 
     switch self { 
      case .one: 
       return "one" 
      case .two: 
       return "two" 
     } 
    } 
} 
+0

重寫localizedDescription不工作的方式(除非你施放的錯誤具體的processError)在問題的上面鏈接比較。 –

+0

@MartinR謝謝。我刪除了這部分答案。我將把它留在協議問題上。 – rmaddy

相關問題