Reputation: 197
am exposing swift API's in Objective-C and the Objective-C runtime.
When i add "@objc" before the function throws an error "Method cannot be marked @objc because its result type cannot be represented in Objective-C"
My code is here
@objc public static func logIn(_ userId: String) -> User? { }
User is optional struct. how to solve this.
Upvotes: 12
Views: 25664
Reputation: 1755
The key bit of information is this:
User is optional struct
If User
is a struct, then it can't be represented in Objective-C, just the same as a Swift class that doesn't inherit from NSObject
.
In order for the method logIn(_:)
to be able to be marked @objc
, then every type referenced in the method declaration has to be representable in Objective-C. You're getting the error message because User
isn't.
To fix it, you're either going to have to change the declaration of User
from this:
struct User {
// ...
}
...to this:
class User: NSObject {
// ...
}
...or redesign logIn(_:)
so that it doesn't return a User
.
You can find more information about this here. In particular, this answer offers the following potential solution:
The best thing i found was to wrap in a Box class
public class Box<T>: NSObject { let unbox: T init(_ value: T) { self.unbox = value } }
Upvotes: 11
Reputation: 79646
Your class or protocol, must be inherited (extended) by NSObject
or anyother class in its hierarchy, containing your code (function) with @objc
notation.
Example:
class TestClass {
public static func logIn(_ userId: String) -> User? { }
}
To use/declare @objc
with this function, class must extend NSObject
(or any other class in its hierarchy)
class TestClass {
@objc public static func logIn(_ userId: String) -> User? { }
}
struct
may not work with optional value in Objective-C, as a work around, you should change User
from struct
to class
Try following code and see:
public class User : NSObject {
// Your code
}
public final class Manager : NSObject {
@objc public static func logIn(_ userId: String) -> User? {
return nil
}
}
Here is snapshot with editor
Upvotes: 0
Reputation: 1374
Only an NSObject-derived class type can be seen by Objective-C. Use:
class User : NSObject {
}
Upvotes: -1
Reputation: 39988
Change the definition of your class as below
class User: NSObject {
}
In this way this class will be available in Objective-C
Upvotes: 3