2015-04-16 100 views
3

我尽量让自定义响应序列与Alamofire类型“X”不符合协议“ResponseObjectSerializable”

我跟着写自述什么,并创建协议和扩展

@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) 
     }) 
    } 
} 

但是当我尝试顺应它,我得到这个错误类型“my_model_class”不符合协议“ResponseObjectSerializable”

我的模型只是一个裸骨类

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

将此与Xcode 6.3一起使用,任何人都会遇到这种情况?并知道如何使这项工作?

响应 到@airspeed错误消失,但什么困惑我的是苹果斯威夫特文件中,他们对@objc协议和符合迅速类的例子并不需要@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 
     } 
    } 
} 

回答

2

Shot没有标记为@objc,不像协议,所以你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

棒的@objcShot前面定义的,它应该编译。

+1

错误消失了,但是令我困惑的是在Apple Swift文档中他们有一个关于'@ objc'协议的例子,并且符合它的swift类不需要'@ objc'。我编辑问题并添加代码。 – sarunw

相关问题