Home > AI > Language > Swift >

NSClassFromString(_:)

Example 1: need name space

// have to be class, not struct ( it has no required init)
class Person {
    var name: String = "good"
    
    // required
    required init(){
    }
}
func classFromString(_ className: String) -> AnyClass! {

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

    return cls
}
let cls = classFromString("Person") as! Person.Type
let instance = cls.init()
print(instance.name)

Example 2: don’t need name space

import Foundation

// add this
@objc(Person)
class Person: NSObject {
    var name: String = "good"
    
    // required
    required override init(){
    }
}
let cls = NSClassFromString("Person") as! Person.Type
let instance = cls.init()
print(instance.name)

Leave a Reply