给出以下函数:
class func collection(#response: NSHTTPURLResponse,
representation: AnyObject) -> [City] {
return []
}
所以这个函数应该返回一个城市对象数组。我必须以某种方式将 AnyObject 类型的表示变量转换为城市数组。
我不知 Prop 体的表示类型是什么,但我可以做类似的事情
println(representation[0])
它将打印该对象。有什么想法如何将表示形式转换为 [City] 数组吗?
更新
正在做
println(representation as [City])
打印 nil。
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)
})
}
}
最佳答案
您返回的 representation
参数是调用 NSJSONSerialization.JSONObjectWithData...
的结果,因此它是一个 NSArray
或 NSDictionary
。由于您获得了 representation[0]
的值,我们知道它是一个 NSArray
。您的代码到底是什么样子取决于 JSON(您应该在这样的问题中包含一个示例),但您的代码需要类似于(前面未经测试的代码):
class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [City] {
var cities: [City] = []
for cityRep in representation {
// these next two lines should grab the city data using the correct key
let id = cityRep.valueForKey("cityID") as String
let name = cityRep.valueForKey("cityName") as String
// now add the city to our list
cities.append(City(id: id, name: name))
}
return cities
}
关于ios - AnyObject 快速数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26703465/