Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method cannot be marked @objc because its result type cannot be represented in Objective-C

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.

like image 362
SriMa Avatar asked Mar 29 '18 09:03

SriMa


2 Answers

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
    }
}
like image 87
Søren Mortensen Avatar answered Oct 21 '22 15:10

Søren Mortensen


Change the definition of your class as below

class User: NSObject {

}

In this way this class will be available in Objective-C

like image 29
Inder Kumar Rathore Avatar answered Oct 21 '22 14:10

Inder Kumar Rathore