Swift转换为具有约束的泛型类型

时间:2022-09-11 10:35:54

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

我使用带有约束泛型的Swift 3(即where子句)。当我尝试进行泛型类型转换时,我遇到了问题。以下是该问题的简化示例:

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.

我的问题是当我从方法返回时,编译器抱怨它无法将类型[T]转换为类型[T:DomainResource]。如果我从泛型中删除DomainResource约束,它编译并运行就好了。

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.

斯威夫特似乎不知道这意味着什么。有关如何解决这个问题的任何想法?如果可能的话,我不想将它们全部转换为DomainResource对象。

1 个解决方案

#1


1  

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:

这表示jsonToObj(jsonStr :)方法返回一个字典,其键的类型为T,其值为DomainResource类型。看起来你只想写这个函数签名:

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

#1


1  

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:

这表示jsonToObj(jsonStr :)方法返回一个字典,其键的类型为T,其值为DomainResource类型。看起来你只想写这个函数签名:

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