[英]AnyObject to array in swift
给出以下功能:
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)
})
}
}
您要返回的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
}
假设(尽管我不愿做假设,但您的问题在细节上有些含糊),表示形式是表示响应的NSData对象,还是从响应创建的数组。
以我的经验,这样的响应是一系列字典,可用于创建城市对象。 因此,您需要编写一个函数将此字典转换为City
对象。 有签名的东西:
parser (AnyObject) -> City
现在,您可以遍历数组,将此函数应用于每个字典,将结果收集到Array中并返回结果。
但是您可能会更经典,并在数组上映射函数并返回结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.