Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift class in Objective-C: unknown receiver

I wrote a class in a swift-file:

class UtilityMethods {
    class func userId() -> Integer {        
        ...
    }

    class func setUserId(userId : Int) {
        ...
    }
}

I'm importing the -swift.h-header which compiles fine, but I can't use

[UtilityMethods userId];

in my Objective-C code:

Unknown receiver 'UtilityMethods'; did you mean 'UtilMethods'?

UtilMethodsis an Objective-C class I'd like to replace. Am I missing something?

EDIT With the help of Lance, the class is now recognized, but the getter method isn't, unfortunately, the header files looks like the following:

SWIFT_CLASS("_TtC15...14UtilityMethods")
@interface UtilityMethods : NSObject
+ (void)setUserId:(NSInteger)userId;
- (instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

Why is the getter missing?

like image 811
swalkner Avatar asked Oct 01 '22 13:10

swalkner


2 Answers

In order to have a Swift class available to Objective C you have two options:

Option 1: Subclass NSObject (or some other Objective C class)

class UtilityMethods : NSObject {
    class func userId() -> Int {
        ...
    }

    class func setUserId(userId: Int) {
        ...
    }
}

Option 2: Add the @objc attribute to your class telling the Swift compiler to make an Objective C object that uses dynamic dispatch rather than static dispatch for method calls

@objc class UtilityMethods {
    class func userId() -> Int {
        ...
    }

    class func setUserId(userId: Int) {
        ...
    }
}
like image 171
Lance Avatar answered Oct 03 '22 02:10

Lance


In my case, I was doing @objc correctly, but in changing from my old Objective-C .h file to my new swift file, I had accidentally lost the Target Membership of the new file, so it wasn't being included in the build.

like image 27
Oded Avatar answered Oct 03 '22 02:10

Oded