ios - 在 Swift 中使用字符串将类分配给变量

标签 ios swift class

我正在尝试快速解决一些欧拉项目问题。 我最初尝试使用 Playground,但发现它非常慢,所以我制作了一个简单的单 View 应用程序,它将在模拟器中为我运行它们。请参阅下面的示例:

enter image description here

我这样做的方法是创建一个名为 ProblemClass 的客户类,然后为从该类继承的每个问题创建一个新类。之后,我所要做的就是重写 ProblemClass 中的函数,然后 View Controller 只需从继承自 ProblemClass< 的 Problem1 类加载所有信息.

当它转至从 Problem1(或任何其他问题)加载的 View 时,它会通过我在转场期间设置 currentProblem 变量来获取详细信息。见下文

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

有没有一种方法可以为 Problem#() 分配一个字符串,这样我就不必制作数百个这样的案例?我不知道它会是什么样子,并且尝试使用 google 不断返回有关#selectors 的答案。我不知道它到底会是什么样子,但在我的脑海里,我在想这样的事情。

destination.currentProblem = Class(name: "Problem4")

如果我的问题不清楚,请告诉我,我会尽力解释得更好。 提前致谢!

---编辑--- 从下面选择的答案中添加我的解决方案。

所以我将 prepare 函数更改为:

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

为了在我的 ProblemClass 中获取 init(),我让我的类看起来像这样:

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"]
}
}

最佳答案

也许:

let problemNumber: Int = 1
var className = "AppName.Problem\(problemNumber)"
let problemClass = NSClassFromString(className) as! Problem.Type
destination.currentProblem = problemClass

关于ios - 在 Swift 中使用字符串将类分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50263313/

相关文章:

ios - 在 swift 3 中传递地址时在 map 中获取 "Cannot provide direction"?

ios - Objective-C 删除 ANSI 颜色控制代码

ios - Coreplot iOS - 删除饼图周围的边框线

ios - 授权给 HealthKit 时,错误 '(_, _) -> Void' 无法转换为 'HealthManager'

java - 添加两个对象——难以理解接受一个对象作为参数

ios - 如何访问 objective-c 文件中的 swift 类

ios - UITableview 在滚动之前需要多次尝试滚动

swift - Realm + NSTableView + NSArrayController

php限制函数调用某些类

java - 如何创建嵌套在静态类中的类的实例,该类又嵌套在非静态类中?