Skip to main content
 首页 » 操作系统

ios之Swift 枚举运算符重载

2024年01月01日45shanyou

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

我阅读了一些主题,但没有找到任何明确的答案。 我还在常量类之外为枚举声明了运算符重载函数。

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>>

请您参考如下方法:

这是典型的可选问题:当您查询字典时,它会返回一个可选值,以解决找不到键的情况。所以这个:

Constants.pieceMapping[self.pieceValue] 

属于 Array<String>?类型。为了访问该数组,您首先必须使用强制解包从可选解包:

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

或者以更安全的方式使用可选绑定(bind):

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