Swift枚举运算符重载

时间:2014-10-28 11:36:02

标签: ios swift

我已经定义了一个枚举,我想将它用作字典的键。 当我尝试使用枚举作为键来访问值时,我得到一个关于枚举不能转换为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>>

1 个答案:

答案 0 :(得分: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]
}