Objective-C Call Swift Function

Call Swift function from Objective-C class

Problem Solved, I previously create and included a new .h file in my Objective-C class named <ProductModuleName>-Swift.h but, as i discovered later, this step is not necessary because the compiler creates the necessary file invisible.

Simply include <ProductModuleName>-Swift.h in your class and it should work.

Syntax to Call Swift Method from Objective-C Class

In swift 4.2 and latest

  1. Add this line to your "*.m" file:

    #import "YourProjectName-Swift.h"
  2. Add @objc before your function:

    @objc public func imageFromString(name: String?) -> UIImage? {    
    //code to make the image
    return image
    }
  3. Call it inside Objective-C class:

    ImageClass *imgObject = [[ImageClass alloc] init];   
    UIImage *myImage = [imgObject imageFromStringWithName:@"test"];

Call Swift function with parameters from Objective C class

  1. You must call alloc before init call.

    MySwiftClass* instance = [[MySwiftClass alloc] initWithFirstName: @"John" lastName: @"Doe"];
  2. Mark method with @objc or use @objcMembers to make your method exposable from Objective-C code. And unfortunately you can't user throwable initializers in Objective-C.

    @objcMembers class MySwiftClass: NSObject {
    var firstName : String
    var lastName: String

    public init(firstName: String, lastName: String) throws {
    guard !firstName.isEmpty && !lastName.isEmpty else { throw SOME_ERROR }
    self.firstName = firstName
    self.lastName = lastName
    super.init()
    }

    func methodWithParams(city: String, suburb: String) throws -> String {
    return city + suburb
    }
    }

Call Swift function with multiple arguments form Objective-C syntax

You can try

[imgObject getImageCalledWithName:myname width:30];  

Calling Swift class method from Objective-C

Essentially the NSObject is the base object type in Apple development.

The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.

Your class defines like that, using NSObject supper class (related to your requirements).

class ClassName: NSObject {

class func someFunction(idValue: Int, completionHandler: @escaping (_ jsonData: String) -> ()) {

}
}

call this function

[ClassName someFunctionWithIdValue:12 completionHandler:^(NSString * test) {

}];


Related Topics



Leave a reply



Submit