Lory Huz
Lory Huz

Reputation: 1508

How to use Swift non-NSObject subclass in Objective-C

I'm experiencing some issues to use Swift in my Objective-C project.

I use the following lib for example (https://github.com/Hearst-DD/ObjectMapper). I've tried the thing to add @objc directive before my subclass but it's say that only classes that inherit from NSObject can be declared @objc. Seems it's related only to Swift 2.0

So my question is, how I can use pure swift classes or libraries in my Objective-C projet ? If it's stil possible ...

My model looks like this: import Foundation import ObjectMapper

class SSStreetAddressRequest: Mappable {

    var street:String?
    var city:String?
    var state:String?
    var zip:String?

    required init?(_ map: Map){

    }

    func mapping(map: Map) {
        street  <- map["street"]
        city    <- map["city"]
        state   <- map["state"]
        zip     <- map["zip"]
    }
}

Mappable is a protocol: https://github.com/Hearst-DD/ObjectMapper/blob/master/ObjectMapper/Core/Mapper.swift

Upvotes: 0

Views: 3307

Answers (1)

Bj&#246;rn Ro
Bj&#246;rn Ro

Reputation: 780

In Objective-C you cannot create a class without a superclass. Thats why the @objc will not work without at least NSObject.

So you have to use at least NSObject. Thats how i would do it

@objc class SSStreetAddressRequest: NSObject {
    var street:String?
    var city:String?
    var state:String?
    var zip:String?
}

extension SSStreetAddressRequest : Mappable {
    required init?(_ map: Map){

    }

    @objc func mapping(map: Map) {
        street  <- map["street"]
        city    <- map["city"]
        state   <- map["state"]
        zip     <- map["zip"]
    }
}

Upvotes: 5

Related Questions