I'm working to create a SpriteKit game and I'm trying to choose an enum value with a function inside my enum so that I can use each value outside of it.
This is my code:
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)!)
}
}
I can't choose anything but the circle.
Any ideas on how to solve that?
The function useGeometry
returns .Circle
every time because you start it with rawValue 0, which is the result of Int()
.
Implement that funcion to return self
(shoud not be static anymore) and use shapeType
in the switch.
The problem is this function:
static func useGeometry() -> Classification {
return Classification(rawValue: Int())!
}
You are creating a new Classification with a rawValue evaluated by Int(), which is going to return a new Int object with a default value (Int() == 0).
So when you call useGeometry from your switch statement, it's effectively always going to return .Circle, because the rawValue is effectively always 0.
You probably want to pass in an integer, eg maybe the row value?, to useGeometry, something which matches up to a Classification enum value. Something like this:
static func useGeometry(value: Int) -> Classification {
return Classification(rawValue: value)!
}
Note: Be careful that you don't call it with an invalid value or you will crash, because you're force unwrapping the result of the constructor. And then call it with a value:
switch Classification.useGeometry(value: shapeStartingRow) {
...
}
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.