I'm trying to do some of the project Euler problems in swift. I originally tried using the Playground, but found that to be incredibly slow, so I've instead made a simple single view app that will run them for me in the simulator. See below for my example:
The way I did this was I made a customer class called ProblemClass and then I make a new class for each problem that inherits from that class. After that, all I have to do is override the functions in ProblemClass and then the View Controller just loads all the information from the Problem1 Class that inherited from ProblemClass.
When it segue's to the view that loads from Problem1 (or any other problem), it gets the details by me setting the currentProblem variable during the segue. see below
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as! ProblemVC
let cell = sender as! ProblemsTVCell
let label = cell.label!
switch label.text! {
case "Problem 1":
destination.currentProblem = Problem1()
case "Problem 2":
destination.currentProblem = Problem2()
case "Problem 3":
destination.currentProblem = Problem3()
case "Problem 4":
destination.currentProblem = Problem4()
default:
break
}
}
Is there a way to assign the Problem#() with a string, so I don't have to make hundreds of these cases? I have no idea what it would look like, and trying to google kept returning answers about #selectors. I don't know what it really would look like, but in my mind I'm thinking something like this.
destination.currentProblem = Class(name: "Problem4")
Let me know if what I'm asking isn't clear and I'll try to explain better. Thank you in advance!
---EDIT--- Adding in my solution from the selected answer below.
So I changed the prepare function to this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as! ProblemVC
let cell = sender as! ProblemsTVCell
let label = cell.label!
let problemName = label.text!.replacingOccurrences(of: " ", with: "")
let problemClass = NSClassFromString("Project_Euler.\(problemName)")! as! ProblemClass.Type
destination.currentProblem = problemClass.init()
}
And to get the init() in my ProblemClass I made my class look like this:
class ProblemClass {
required init() {
return
}
func title() -> String {
return "Title"
}
func problem() -> String {
return "Problem #"
}
func question() -> [String] {
return ["No Question Yet"]
}
func answer() -> [String] {
return ["No Answer Code Entered Yet"]
}
}
