How to create an instance of a class from a String in Swift

前端 未结 4 1350
终归单人心
终归单人心 2020-12-08 19:47

I have tried creating an instance of a class using a string in numerous ways with none of them working in Swift 3.

Below are pre-Swift 3 sol

4条回答
  •  时光取名叫无心
    2020-12-08 20:04

    If you project contains space you should replace space with '_'

    Something like this

    let namespace = (Bundle.main.infoDictionary!["CFBundleExecutable"] as! String).replacingOccurrences(of: " ", with: "_")
    let cls = NSClassFromString("\(namespace).\(className)")! as! AnyClass
    

提交回复
热议问题