这是一个包含游戏中启用的操作的结构:
struct OperationsEnabled {
var addition = 1
var subtraction = 0 // disabled
var multiplication = 1
var division = 1
}
这是我用来生成简单算术问题的枚举:
enum BinaryOperation: String {
case Addition = "+"
case Subtraction = "-"
case Multiplication = "×"
case Division = "÷"
func rangesForDifficulty(difficulty: Difficulty) -> (Range<Int>, Range<Int>) {
switch self {
case .Addition:
switch difficulty {
case .Easy: return (1...10, 1...10)
case .Intermediate: return (10...100, 1...100)
case .Difficult: return (109...999, 109...999)
}
case .Subtraction:
switch difficulty {
case .Easy: return (1...10, 1...10)
case .Intermediate: return (10...100, 1...100)
case .Difficult: return (109...999, 109...999)
}
case .Multiplication:
switch difficulty {
case .Easy: return (1...10, 2...4)
case .Intermediate: return (1...50, 3...7)
case .Difficult: return (10...100, 4...15)
}
case .Division:
switch difficulty {
case .Easy: return (1...10, 2...4)
case .Intermediate: return (1...50, 3...7)
case .Difficult: return (10...100, 4...15)
}
}
}
func apply(number1: Int, _ number2: Int) -> Int {
switch self {
case .Addition:
return number1 + number2
case .Subtraction:
return number1 - number2
case .Multiplication:
return number1 * number2
case .Division:
return number1 / number2
}
}
}
// Let's make a new question
func newQuestion() {
let (range1, range2) = binaryOperation.rangesForDifficulty(difficulty)
let number1 = Int.random(range1)
let number2 = Int.random(range2)
let answer = binaryOperation.apply(number1, number2)
}
我想过滤掉这些操作。例如,我需要排除游戏中不允许的操作,但似乎没有办法在这里使用条件。我该怎么办?
答案 0 :(得分:1)
您想从可用操作中选择随机操作。为BinaryOperation
创建一个初始化程序,其OperationsEnabled
并创建BinaryOperation
。
init?(enabled: OperationsEnabled) {
let all: [(BinaryOperation, Int)] = [(.Addition, enabled.addition), (.Subtraction, enabled.subtraction),
(.Multiplication, enabled.multiplication), (.Division, enabled.division)]
let avail = all.flatMap { (op, on) in on == 1 ? op : nil }
if avail.isEmpty {
return nil
}
else {
let index = Int(arc4random_uniform(UInt32(avail.count)))
self = avail[index]
}
}
let enabled = OperationsEnabled(addition: 1, subtraction: 1, multiplication: 0, division: 0)
let binaryOperation = BinaryOperation(enabled: enabled)!
flatMap
用于仅选择可用的操作。avail
将为空,此可用初始值设定项将返回nil
。答案 1 :(得分:0)
转换语句需要&#34;穷举&#34;即涵盖所有可能的案例/枚举。所以你最好的选择就是使用if
或使用default
案例,这将满足你没有明确定义自己的任何情况(在这种情况下你想要的那些& #39;过滤器&#39)