【发布时间】:2014-11-02 19:35:48
【问题描述】:
给出以下函数:
class func collection(#response: NSHTTPURLResponse,
representation: AnyObject) -> [City] {
return []
}
所以这个函数应该返回一个城市对象数组。我必须以某种方式将 AnyObject 类型的 representation 变量转换为城市数组。
我不知道确切的表示类型是什么,但我可以做类似的事情
println(representation[0])
它会打印对象。任何想法如何将表示转换为 [City] 数组?
更新
在做
println(representation as [City])
打印为零。
City.swift:
final class City : ResponseCollectionSerializable {
let id: String
let name: String
class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [City] {
return []
}
}
这只是从https://github.com/Alamofire/Alamofire#generic-response-object-serialization复制和粘贴它应该将JSON响应序列化为对象:
@objc public protocol ResponseCollectionSerializable {
class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}
extension Alamofire.Request {
public func responseCollection<T: ResponseCollectionSerializable>(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.collection(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)
})
}
}
【问题讨论】:
-
可能表示为 [City]。但我认为你应该先找出代表的实际班级
-
@AndreyChernukha 查看我更新的问题。