Search code examples
swiftbundlebundles

Call Swift function from Bundle


I have declared a function in a custom bundle using Xcode and Swift.

MyBundle.bundle —> File.swift —> func …() {}

How do I call that function from another project using Foundation.Bundle?


Solution

  • Well you can't call it directly but probably you can make some way around that might work.

    You can create an instance of that class from string using NSClassFromString and then you call the method using that call

    Something like below

    func getClassName(_ strClassName: String) -> AnyClass! {
       let bundle = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
        let requiredClass: AnyClass = NSClassFromString("\(namespace).\(strClassName)")!;
        return requiredClass;
    }
    

    Then you can call the method using your class instance returned by the above method like

    yourClassInstance.perform(Selector("functionName"))