ios - AnyObject 快速数组

标签 ios swift

给出以下函数:

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... 的结果,因此它是一个 NSArrayNSDictionary。由于您获得了 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/

相关文章:

ios - 将用户文本字段输入附加到其他 View Controller 中的数组中

iphone - 来自编码未知的文本文件的 NSString

ios - 图片来自颜色问题

具有核心数据、照片和 iCloud 的 iOS 应用程序

ios - Swift:如何使用标签访问 UITextField 属性

ios - UIScrollView 中仅水平缩放 UIView

ios - 如何调用 id 类型的对象上的方法

ios - 以数组形式快速从解析中提取数据

swift - 如何使用 Swift 从 Firebase DB 引用路径中删除观察者?

objective-c - Linux 上的 Swift Objective-C 互操作性,错误 : 'Foundation/Foundation.h' file not found