My Swift实现的异步方法如下:
import Foundation
import AlamofireObjectMapper
import Alamofire
@objc class ServerManager : NSObject {
@objc static let sharedInstance = ServerManager()
override init() {
}
func getList(lat:Double, lon:Double,handler: @escaping (Lists?,Error?)->Void) {
Alamofire.request(ServerRequestRouter.getDataList(lat, long))
.responseArray(keyPath:"searchList") {(response:DataResponse<Lists>) in
switch response.result {
case .success:
if let data = response.result.value {
handler(data, nil)
}
case .failure(let error):
handler(nil,error)
}
}
}
}
当然这在Swift中工作正常,但是现在我想从Objective-C类中调用它,所以我的问题是如何更改它以便可以从Objective-C调用它?
我尝试了什么?
@objc func getList(lat:Double, lon:Double,handler: @escaping (Lists?,Error?)->Void) {
Alamofire.request(ServerRequestRouter.getDataList(lat, long))
.responseArray(keyPath:"searchList") {(response:DataResponse<Lists>) in
switch response.result {
case .success:
if let data = response.result.value {
handler(data, nil)
}
case .failure(let error):
handler(nil,error)
}
}
}
错误:无法将方法标记为@objc,因为参数3的类型无法在Objective-C中表示。
无法表示的类型是闭包:@escaping (Lists?,Error?)->Void
如何更改以便能够从Objective调用。
注意:从Objective-C对Swift方法的其他调用工作正常,我只是遇到了对Objective-C的Swift闭包可操作性的问题。
编辑:列表是Mappable结构的集合:
import Foundation
import ObjectMapper
import AlamofireObjectMapper
typealias Lists = [Item]
struct Item : Mappable
{
public var id: Int!
public var name: String!
public var address: String!
init?(map: Map)
{
}
mutating func mapping(map: Map)
{
id <- map["identifier"]
name <- map["name"]
address <- map["address"]
}
}
答案 0 :(得分:0)
好吧,我让这个工作。我只需要将我的模型结构转换为一个继承自NSObject的类,并在扩展中实现Mappable
协议:
import Foundation
import ObjectMapper
import AlamofireObjectMapper
typealias Lists = [Item]
@objc class Item : NSObject
{
public var id: Int!
public var name: String!
public var address: String!
required init?(map: Map)
{
}
}
extension Item : Mappable
{
func mapping(map: Map)
{
id <- map["identifier"]
name <- map["name"]
address <- map["address"]
}
}