Swift是否无法使用泛型类型来专门化泛型类型?

时间:2016-03-01 02:16:29

标签: json swift generics alamofire objectmapper

我正在使用Alamofire + AlamofireObjectMapper以及ObjectMapper使用JSON API(Reddit)。我正在努力创建模型,并提出一个不能按预期工作的建议解决方案。我会尽力解释......

我收到的JSON响应有一个基类Thing,如下所示

class Thing<T where T:Mappable>: Mappable {

    var id: String?
    var name: String?
    var kind: String?
    var data: T?

    required init?(_ map: Map) {}

    func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
        kind <- map["kind"]
        data <- map["data"]
    }
}

data属性因我提出的请求类型而异。在这种特殊情况下,它应该是Listing类型,如下所示。

class Listing<T where T: Mappable>: Mappable {

    var before: String?
    var after: String?
    var modhash: String?
    var children: [Thing<T>]?

    required init?(_ map: Map) {}

    func mapping(map: Map) {
        before   <- map["before"]
        after    <- map["after"]
        modhash  <- map["modhash"]
        children <- map["children"]
    }
}

children属性是Thing个对象的数组,但data为不同的类型,在这种情况下为Post

class Post: Mappable {
    var author: String?
    var creationDate: Int?
    var name: String?
    var numberOfComments: Int?
    var score: Int?
    var text: String?
    var stickied: Int?
    var subreddit: String?
    var title: String?
    var url: String?
    var preview: Images?

    required init?(_ map: Map) {}

    func mapping(map: Map) {
        author <- map["author"]
        creationDate <- map["created_utc"]
        name <- map["name"]
        numberOfComments <- map["num_comments"]
        score <- map["score"]
        text <- map["selftext"]
        stickied <- map["stickied"]
        subreddit <- map["subreddit"]
        title <- map["title"]
        url <- map["url"]
        preview <- map["preview"]
    }
}

使用AlamofireObjectMapper扩展,将JSON响应解析为我的自定义模型,我们使用

public func responseObject<T : Mappable>(keyPath: String? = default, completionHandler: Alamofire.Response<T, NSError> -> Void) -> Self

它期待泛型类型。我将使用定义为Response<Thing<Listing<Post>>, NSError>的类型,如下所示......

RedditAPIService.requestSubReddit(subReddit: nil, withSortType: .Hot, afterPost: nil, postsAlreadyShown: nil).responseObject { (response: Response<Thing<Listing<Post>>, NSError>) -> Void in
            if let value = response.result.value {
                print(value.kind)
            }
        }

我看到的问题是Listing对象上的数据损坏。

DebugIMG

我期待children对象中只有1个值,而不是&gt; 900 Zillion!

我知道我可以将ThingListing子类化为特定类型,但我也很好奇为什么这不能按预期工作。有任何想法吗?谢谢!

0 个答案:

没有答案