简体   繁体   中英

Swift Cast to Generic Type with Constraint

I am using Swift 3 with constrained generics (ie a where clause). I have a problem when I am trying to do generic type casting. Here is a simplified example of the problem:

func jsonToObj<T:DomainResource>(jsonStr: String) -> [T:DomainResource] {
    let json = JSON(parseJSON: jsonStr).dictionaryObject
    let bundle = SMART.Bundle(json: json)

    let result = bundle.entry?.map() {
        return $0.resource as! T
    }

    return result!
}

My problem is when I return from the method, the compiler complains its cannot convert type [T] to type [T:DomainResource] . If I remove the DomainResource constraint from the generic, it compiles and runs just fine.

That's not what I want, so, I tried this:

let result = bundle.entry?.map() {
    return $0.resource as! T:DomainResource
}

Swift doesn't seem to know what that means. Any idea on how to work around this problem? I'd like to not just cast them all to DomainResource objects, if possible.

You wrote this function signature:

func jsonToObj<T:DomainResource>(jsonStr: String) -> [T:DomainResource]

This says that the jsonToObj(jsonStr:) method returns a dictionary whose keys are of type T and whose values are of type DomainResource . It looks like you just want to write this function signature:

func jsonToObj<T:DomainResource>(jsonStr: String) -> [T]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM