Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Swift function with more than one parameter from Objective C class?

For example I have this method in swift:

@objc class MyClass: NSObject
....
@objc class func viewWithIndex(index: Int, str: String) {
    println(index, str)
}

then i wanna call that method in my objective-c class, and i was expecting as simple as this call [MyClass viewWithIndex:10 str:@"string"]; but it doesn't work.

How do i call it? Please help.

Note: I have already a working swift function call to objective-c [MyClass showSomething]; so that means i have successfully setup necessary settings to bridge classes. Only the function that has two of more parameters is my problem. :)

Solved:

I dont know what i happened but i just restarted my mac and removed objc and it worked with the call [MyClass viewWithIndex:10 str:@"string"];. I remember reading in documentation.

Migrating Your Objective-C Code to Swift

  • To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.
like image 661
Arnlee Vizcayno Avatar asked Sep 17 '14 09:09

Arnlee Vizcayno


People also ask

Can you use Swift and Objective-C together?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

How do you subclass a Swift class in Objective-C?

Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs: You cannot subclass a Swift class in Objective-C.


1 Answers

This worked for me in Swift 3.0

public class func viewWithIndex(_ index: Int, str: String) {
    println(index, str)
}

Adding the underscore before the first parameter in the Swift declaration allowed me to call from objective c without naming the first parameter, like this:

[MyClass viewWithIndex:10 str:@"string"]
like image 182
haplo1384 Avatar answered Oct 18 '22 00:10

haplo1384