我正在努力创建一个 SpriteKit 游戏,我试图在我的枚举中选择一个带有函数的枚举值,以便我可以在它之外使用每个值。
这是我的代码:
enum Classification: Int, CustomStringConvertible {
case Circle = 0, Square, Triangle
var classificationName: String {
switch self {
case .Circle:
return "circle"
case .Square:
return "square"
case .Triangle:
return "triangle"
}
}
var description: String {
return self.classificationName
}
var classificationSpriteName: String {
let classificationSpriteName = [
"circle",
"square",
"triangle"
]
return classificationSpriteName[rawValue]
}
static func useGeometry() -> Classification {
return Classification(rawValue: Int())!
}
}
class Shape: CustomStringConvertible, Hashable {
var hashValue: Int {
return self.column ^ self.row
}
var column: Int
var row: Int
let shapeType: Classification
var shapeSprite: SKSpriteNode?
var classificationName: String {
return shapeType.classificationName
}
….(code)…
final class func chosenShape(shapeStartingColumn:Int, shapeStartingRow:Int) -> Shape {
switch Classification.useGeometry() {
case .Circle:
return CircleShape(column:shapeStartingColumn, row:shapeStartingRow, shapeType: Classification(rawValue: 0)!)
case .Square:
return SquareShape(column:shapeStartingColumn, row:shapeStartingRow, shapeType: Classification(rawValue: 1)!)
case .Triangle:
return SquareShape(column:shapeStartingColumn, row:shapeStartingRow, shapeType: Classification(rawValue: 2)!)
}
}
我只能选择圆圈。
关于如何解决这个问题有什么想法吗?
最佳答案
问题是这个函数:
static func useGeometry() -> Classification {
return Classification(rawValue: Int())!
}
您正在创建一个新的分类,其原始值由 Int() 求值,它将返回一个具有默认值 (Int() == 0) 的新 Int 对象。
因此,当您从 switch 语句调用 useGeometry 时,它实际上总是会返回 .Circle,因为 rawValue 实际上始终为 0。
您可能希望将一个整数(例如行值)传递给 useGeometry,它与 Classification 枚举值相匹配。像这样:
static func useGeometry(value: Int) -> Classification {
return Classification(rawValue: value)!
}
注意:请注意不要使用无效值调用它,否则会崩溃,因为您是在强制展开构造函数的结果。 然后用一个值调用它:
switch Classification.useGeometry(value: shapeStartingRow) {
...
}
关于ios - 如何在 Swift 的枚举中选择一个带有函数的枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52044702/