2014-10-28 93 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