本文介绍了如何在Objective-C中使用Swift非NSObject子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Objective-C项目中遇到一些使用Swift的问题。

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

我使用下面的lib作为示例()。我已经尝试过在我的子类之前添加@objc指令,但是它说只有从NSObject继承的类才可以声明为@objc。似乎它只与Swift 2.0有关

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

所以我的问题是,我如何在Objective-C项目中使用纯粹的swift类或库?如果它可能... ...

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

我的模型如下所示:
import Foundation
import ObjectMapper

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是一种协议:

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

推荐答案

在Objective-C中,你不能创建没有超类的类。这就是为什么@objc在没有至少NSObject的情况下无法工作的原因。

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

所以你必须至少使用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"]
    }
}

这篇关于如何在Objective-C中使用Swift非NSObject子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:53