2015-04-16 143 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

相關問題