gpt4 book ai didi

ios - 在 Swift 中删除/排除枚举案例

转载 作者:行者123 更新时间:2023-11-28 06:40:31 26 4
gpt4 key购买 nike

这是一个包含游戏中启用的操作的结构:

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)
}

我想过滤掉操作。例如,我需要排除游戏中不允许的操作,但这里似乎没有办法使用条件语句。我该怎么做?

最佳答案

您想从可用操作中随机选择一个操作。为采用 OperationsEnabledBinaryOperation 创建一个初始化程序并创建一个 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)!

注意事项:

  1. 其工作原理是首先创建一个元组配对列表,其中包含与其可用性配对的操作。
  2. flatMap 用于仅选择可用的操作。
  3. 如果没有任何操作被标记为可用,则 avail 将为空并且此 failable 初始化程序将返回 nil
  4. 操作是从可用操作列表中随机选择的。

关于ios - 在 Swift 中删除/排除枚举案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38094402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com