I've written a model for an app that generates math facts kids have to solve by evaluating the operation and the difficulty you pass to it at initialization.
I don't like how I am repeating the code that performs the operations. For instance, performAddition()
and performMultiplication()
both perform the same thing. How can I make this model better?
import UIKit
class QuestionGenerator: NSObject {
enum BinaryOperation {
case Addition
case Subtraction
case Multiplication
case Division
}
enum Difficulty {
case Easy
case Intermediate
case Difficult
}
struct Settings {
var binaryOperation: BinaryOperation
var difficulty: Difficulty
}
private var brain: Settings
var number1: Int = 0
var number2: Int = 0
var answer: Int = 0
init(operation: BinaryOperation, difficulty: Difficulty) {
brain = Settings(binaryOperation: operation, difficulty: difficulty)
super.init()
}
func newQuestion() {
switch brain.binaryOperation {
case .Addition:
performAddition()
break
case .Multiplication:
performMultiplication()
break
default: break
// operation not implemented yet
}
}
private func performAddition() {
switch brain.difficulty {
case .Easy:
number1 = Int.random(1...10)
number2 = Int.random(1...10)
case .Intermediate:
number1 = Int.random(10...100)
number2 = Int.random(10...100)
case .Difficult:
number1 = Int.random(109...999)
number2 = Int.random(109...999)
}
answer = number1 + number2
}
private func performMultiplication() {
switch brain.difficulty {
case .Easy:
number1 = Int.random(1...10)
number2 = Int.random(2...4)
case .Intermediate:
number1 = Int.random(1...50)
number2 = Int.random(3...7)
case .Difficult:
number1 = Int.random(10...100)
number2 = Int.random(4...15)
}
answer = number1 * number2
}
}