I have define an enum, and I want to use it as a key for a dictionary. When I'm trying to access a value using the enum as a key, i get an error about the enum not being convertible to DictionaryIndex<Constants.PieceValue, Array<String>>
where Constants.PieceValue is an enum that looks like this:
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
}
I read a few threads but haven't found any clear answers. I also declared the operator overloading function for the enum outside the Constants class.
func == (left:Constants.PieceValue, right:Constants.PieceValue) -> Bool {
return Int(left) == Int(right)
}
This is the line that Xcode complains about:
self.label1.text = Constants.pieceMapping[self.pieceValue][0]
Constants.pieceMapping has the following type: Dictionary<PieceValue, Array<String>>
That's the typical optional problem: when you query a dictionary, it returns an optional value, to account for cases when the key is not found. So this:
Constants.pieceMapping[self.pieceValue]
is of Array<String>?
type. In order to access to that array, you first have to unwrap from the optional, using either forced unwrapping:
Constants.pieceMapping[Constants.PieceValue.BPawn]![0]
or in a safer way using optional binding:
if let array = Constants.pieceMapping[Constants.PieceValue.BPawn] {
let elem = array[0]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.