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

SriMa picture SriMa · Mar 29, 2018 · Viewed 16.5k times · Source

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.

Answer

Søren Mortensen picture Søren Mortensen · Mar 29, 2018

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
    }
}