2014-10-05 64 views
1

我一直在用Xcode遊樂場搞亂Swift。我知道Swift枚舉比它們的Obj-C等價物更強大。所以我想我會做一個枚舉包含顏色作爲成員值,並添加一個枚舉的方法來獲取顏色的十六進制值。枚舉方法調用解析爲「未使用的函數」

但是,我得到一個錯誤 - 「表達式解析爲一個未使用的函數」。我有一種感覺,這可能與該方法接受成員值作爲參數有關,但我可能是錯誤的。代碼如下。有人可以啓發我嗎?

enum Color { 

case Red,Blue,Yellow 

func hexValue (aColor: Color) -> String { //Find hex value of a Color 
    switch aColor { 
    case .Red: 
     return "#FF0000" 
    case .Yellow: 
     return "#FFFF00" 
    case .Blue: 
     return "#0000FF" 
    default: 
     return "???????" 
    } 
    } 
} 

Color.hexValue(Color.Red) //Error: "Expression resolves to an unused function" 

回答

9

添加statichexValue申報創建類型的方法可以從類型被稱爲無實例:

enum Color { 

    case Red,Blue,Yellow 

    static func hexValue (aColor: Color) -> String { //Find hex value of a Color 
     switch aColor { 
     case .Red: 
      return "#FF0000" 
     case .Yellow: 
      return "#FFFF00" 
     case .Blue: 
      return "#0000FF" 
     default: 
      return "???????" 
     } 
    } 
} 

Color.hexValue(Color.Red) // "#FF0000" 

或者你可以通過使它更好計算屬性

enum Color { 

    case Red,Blue,Yellow 

    var hexValue: String { 
     get { 
      switch self { 
       case .Red:  return "#FF0000" 
       case .Yellow: return "#FFFF00" 
       case .Blue: return "#0000FF" 
      } 
     } 
    } 
} 

Color.Red.hexValue // "#FF0000" 
+0

哇 - 我不知道你可以使用這樣的計算屬性。 (我知道你可以做Color.hexValue但不是Color.Red.hexValue)謝謝一堆! – PopKernel 2014-10-06 02:12:34

0

只要閱讀錯誤信息!

let color = Color.hexValue(Color.Red) 

你必須指定返回值的東西

1

您必須將hexValue函數定義爲static,因爲您沒有從實例調用它。

請注意,default大小寫是不必要的,因爲所有可能的值已經在您的switch語句中處理完畢。

但是,快速枚舉比那更強大。這是我將如何實現它,利用原始值的:使用

enum Color : String { 

    case Red = "#FF0000" 
    case Blue = "#FFFF00" 
    case Yellow = "#0000FF" 

    static func hexValue(aColor: Color) -> String { 
     return aColor.toRaw() 
    } 
} 

,並獲得字符串表示:

Color.hexValue(Color.Red) 

hexValue方法是多餘的,雖然,因爲你可以用:

Color.Red.toRaw() 
0

另一種選擇是使用Printable協議並在您的Enum上實現description計算屬性,然後您可以在ju st使用字符串插值引用它的值。

enum Color: Printable { 
    case Red,Blue,Yellow 

    var description: String { 
     get { 
      switch self { 
       case .Red:  return "#FF0000" 
       case .Yellow: return "#FFFF00" 
       case .Blue: return "#0000FF" 
      } 
     } 
    } 
} 

let myColor = "\(Color.Red)"