gpt4 book ai didi

ios - 类型 'X' 不符合协议(protocol) 'ResponseObjectSerializable'

转载 作者:搜寻专家 更新时间:2023-10-31 22:50:40 25 4
gpt4 key购买 nike

我尝试使用 Alamofire 进行自定义响应序列化

我按照 README 中的内容创建协议(protocol)和扩展

@objc public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}

extension Alamofire.Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
let serializer: Serializer = { (request, response, data) in
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
if response != nil && JSON != nil {
return (T(response: response!, representation: JSON!), nil)
} else {
return (nil, serializationError)
}
}

return response(serializer: serializer, completionHandler: { (request, response, object, error) in
completionHandler(request, response, object as? T, error)
})
}
}

但是当我尝试符合它时,我得到了这个错误 Type 'my_model_class' does not conform to protocol 'ResponseObjectSerializable'

我的模型只是一个简单的类

final class Shot: ResponseObjectSerializable {
required init?(response: NSHTTPURLResponse, representation: AnyObject) {
}
}

将其与 Xcode 6.3 一起使用,有人遇到过吗?并知道如何进行这项工作?

回应到@airspeed 错误消失了,但让我困惑的是在 Apple Swift 文档中他们有一个关于 @objc 协议(protocol)的例子和符合它的 swift 类不需要 @objc

@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}

class TowardsZeroSource: CounterDataSource {
func incrementForCount(count: Int) -> Int {
if count == 0 {
return 0
} else if count < 0 {
return 1
} else {
return -1
}
}
}

最佳答案

Shot 未标记为 @objc,与协议(protocol)不同,因此您的 init 不符合要求:

@objc public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}

final class Shot: ResponseObjectSerializable {
@objc required init?(response: NSHTTPURLResponse, representation: AnyObject) {
}
}

导致错误:

note: protocol requires initializer init(response:representation:) with type (response: NSHTTPURLResponse, representation: AnyObject)

  init?(response: NSHTTPURLResponse, representation: AnyObject)`
^

note: candidate is not @objc, but protocol requires it

Shot 的定义前加上一个 @objc,它应该可以编译。

关于ios - 类型 'X' 不符合协议(protocol) 'ResponseObjectSerializable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29680388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com