I want to make an app where I create different levels by changing the speed. But I'm getting "Expected parameter type following ':'" error and I don't know how can I do this with using enum.
enum Difficulty {
case easy(timeInterval: 1)
case medium(timeInterval: 0.6)
case hard(timeInterval: 0.3)
}
@IBAction func easyButton(_ sender: Any) {
}
@IBAction func mediumButton(_ sender: Any) {
}
@IBAction func hardButton(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
}
CodePudding user response:
You can't hardcode associated values for enum cases. Instead, declare a property that would return a desired value for each case:
enum Difficulty {
case easy
case medium
case hard
var timeInterval: TimeInterval {
switch self {
case .easy:
return 1
case .medium:
return 0.6
case .hard:
return 0.3
}
}
}
Usage:
let difficulty: Difficulty = .easy
let timeInterval = difficulty.timeInterval
CodePudding user response:
Your code is not compiled because of wrong syntax. To solve your task you can inherit you enum
from Double
and use rawValue
to get a difficulty value (https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html#ID149).
enum Difficulty: Double {
case easy = 1
case medium = 0.6
case hard = 0.3
}
let timeInterval = Difficulty.medium.rawValue
print(timeInterval) // Prints "0.6"