2014-10-28 94 views
1

我已經定義了一個枚舉,我想將它用作字典的關鍵字。 當我嘗試使用枚舉作爲密鑰來訪問值,我得到一個錯誤有關不轉換爲DictionaryIndex<Constants.PieceValue, Array<String>>枚舉,其中Constants.PieceValue是一個枚舉,看起來像這樣:快速枚舉運算符重載

public enum PieceValue: Int { 
    case Empty = 0, 
    WKing = 16, 
    WQueen = 15, 
    WRook = 14, 
    WBishop = 13, 
    WKnight = 12, 
    WPawn = 11, 
    BKing = 26, 
    BQueen = 25, 
    BRook = 24, 
    BBishop = 23, 
    BKnight = 22, 
    BPawn = 21 
} 

我讀一些線程,但沒有找到任何明確的答案。 我還爲Constants類之外的枚舉聲明瞭運算符重載函數。

func == (left:Constants.PieceValue, right:Constants.PieceValue) -> Bool { 
     return Int(left) == Int(right) 
    } 

這是Xcode的抱怨行:

self.label1.text = Constants.pieceMapping[self.pieceValue][0] 

Constants.pieceMapping有以下類型:Dictionary<PieceValue, Array<String>>

回答

3

這是典型的可選問題:當您查詢字典,它返回一個可選值,用於說明未找到密鑰的情況。所以這個:

Constants.pieceMapping[self.pieceValue] 

Array<String>?類型。爲了訪問該數組,您必須首先從可選拆開包裝,即使用強制解包:

Constants.pieceMapping[Constants.PieceValue.BPawn]![0] 

或以更安全的方式使用可選的結合:

if let array = Constants.pieceMapping[Constants.PieceValue.BPawn] { 
    let elem = array[0] 
} 
+0

感謝您的詳細解釋。儘管有更多的描述性錯誤信息會很好。 – marosoaie 2014-10-28 12:30:55

+0

那麼這個錯誤是描述性的,但它並沒有幫助弄清楚什麼是錯誤的:)有很多這樣的情況 - 通常當它沒有意義時,它是別的東西 – Antonio 2014-10-28 12:34:04