Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Swift function with parameters from Objective C class

I have a library class wrote in swift which should be used in my existing objective-c code. I have created the bridging-header and have define @class MySwiftClass in .h and import "-Swift.h" in .m

a swift class is something similar to this

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

I have faced two problems.

  1. Don't know how to call swift init function on the objective-c class. I have tried MySwiftClass *myClass = [MySwiftClass init];. Up to this, the app can compile. But don't know how to pass the parameters.

  2. I also want to access myClass.methodWithParams(city:"My city", suburb:"My country") in objective-c class.

Appreciate the help!

like image 862
smartsanja Avatar asked Mar 06 '23 07:03

smartsanja


2 Answers

  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
        }
    }
    
like image 71
Igzar Avatar answered Mar 07 '23 20:03

Igzar


To instantiate an object in Objective-C…

NSError *error = NULL;
MySwiftClass *class = [[MySwiftClass alloc] initWithFirstName: @"John"
                                                     lastName: @"Smith" 
                                                        error: &error]

to call the method

[class methodWithParamsWithCity: @"My CIty" suburb: @"My suburb" error: &error];

throws in Swift appends an NSError ** error parameter in Objective-C

like image 24
Ashley Mills Avatar answered Mar 07 '23 22:03

Ashley Mills