[英]Swift enum operator overloading
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: 当我尝试使用枚举作为键来访问值时,我得到一个关于枚举不能转换为
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
}
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.
我还为Constants类之外的枚举声明了运算符重载函数。
func == (left:Constants.PieceValue, right:Constants.PieceValue) -> Bool {
return Int(left) == Int(right)
}
This is the line that Xcode complains about: 这是Xcode抱怨的那条线:
self.label1.text = Constants.pieceMapping[self.pieceValue][0]
Constants.pieceMapping has the following type: Dictionary<PieceValue, Array<String>>
Constants.pieceMapping具有以下类型:
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>?
是
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]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.