簡體   English   中英

Swift枚舉運算符重載

[英]Swift enum operator overloading

我已經定義了一個枚舉,我想用它作為字典的鍵。 當我嘗試使用枚舉作為鍵來訪問值時,我得到一個關於枚舉不能轉換為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>>

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

Constants.pieceMapping[self.pieceValue]

Array<String>? 類型。 要訪問該數組,首先必須使用強制解包來從可選項中解包:

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

或使用可選綁定以更安全的方式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM