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.
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.
I also want to access myClass.methodWithParams(city:"My city", suburb:"My country")
in objective-c class.
Appreciate the help!
You must call alloc before init call.
MySwiftClass* instance = [[MySwiftClass alloc] initWithFirstName: @"John" lastName: @"Doe"];
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
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With