How to call Swift function with several parameters of 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 want to call this method in the objective-c class, and I expected as simple as this call [MyClass viewWithIndex:10 str:@"string"]; but it does not work.

What should I call it? Please, help.

Note. I already have an operational call to the objective-c function [MyClass showSomething]; , so I want to successfully configure the necessary settings for combining classes. My problem is only in a function that has two parameters. :)

It is decided:

I don't know what happened, but I just restarted my mac and uninstalled objc and it worked with a call [MyClass viewWithIndex:10 str:@"string"]; . I remember reading in the documentation.

Porting objective-c code to Swift

  • To be accessible and useful in Objective-C, the Swift class must be a descendant of the objective-c class or must be marked as @objc.
+10
source share
3 answers

This worked for me in Swift 3.0

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

Adding underscore before the first parameter in the Swift declaration allowed me to call c from the lens without naming the first parameter, for example:

 [MyClass viewWithIndex:10 str:@"string"] 
+12
source

I believe that you need to mark the function as public (makes sense) or dynamic. Otherwise, it will become a candidate for Swift optimization (built-in or vtable method), which will make it invisible to Objective-C.

Try the following:

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

Or this: (it doesn't really make sense, but should also work)

 private dynamic class func viewWithIndex(index: Int, str: String) { println(index, str) } 
+3
source

forward your class declaration to .h target-c file

 @class <MySwiftClass> 

import "Productname-swift.h" in class obj-cm use

 [SwiftClass storeWithData:@"Hi" password:@"secret"]; 

SwiftClass.swift

 @objcMembers class SwiftClass{ public class func store(data: String,password:String)->Bool{ let saveSuccessful: Bool = KeychainWrapper.standard.set(data, forKey: password) return saveSuccessful; } } 
0
source

Source: https://habr.com/ru/post/975409/


All Articles