Swift:如何在变量中保存泛型类型的任何可能实例

Ken*_*ner 7 generics swift

我想做的事情的精髓是这样的:

public struct HolderOfWrappers
{
    let anyWrappedItem: MyResource<Any>
}

public struct MyResource<A>
{
    let wrappedItem : A
    let convert: String -> A
}

func holdResource<A>( resource: MyResource<A> ) -> HolderOfWrappers
{
    // Error on this line, A is not Any...
    let wrapHolder : HolderOfWrappers = HolderOfWrappers( resource )
    return wrapHolder
}
Run Code Online (Sandbox Code Playgroud)

就目前情况而言,这段代码在holdResource我尝试构建的最后一个方法中产生了编译器错误HolderOfWrappers

Cannot convert the expression's type 'MyResource<A>' to type '(anyWrappedItem: MyResource<Any>)'
Run Code Online (Sandbox Code Playgroud)

这是可以理解的,因为代码表明 HolderOfWrappers 只能保存为 Any 类型构建的 MyResource,而不是任何可能的类型。我真正想要的HolderOfWrappers是这样的:

public struct HolderOfWrappers
{
    let anyWrappedItem: MyResource<>
}
Run Code Online (Sandbox Code Playgroud)

甚至MyResource<*>- 我试图用这段代码表示我想要一个可以保存任何类型的 MyResource 的变量。如果我尝试使用任何一种语法,我都会收到编译器错误,它需要一个类型。

我可以只拥有anyWrappedItemby of type Any,但随后您会丢失类型信息以供将来使用。我也不希望 HolderOfWrappers 是通用的(因为那样我以后就会遇到同样的问题)。

这几乎就像我试图将泛型类型视为anyWrappedItem存储变量的协议,这由于其他原因而不起作用......

Aar*_*sen 2

我认为您可以通过在方法中添加通用参数来完成您想要的操作HolderOfWrappers init。基本上,该init方法只是MyResource使用resource您提供的生成一个新的,如下所示:

public struct HolderOfWrappers {

    let anyWrappedItem: MyResource<Any>

    public init<A>(resource: MyResource<A>) {
        self.anyWrappedItem = MyResource(wrappedItem: resource.wrappedItem, convert: resource.convert)
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为这会做你想做的。我不知道它是否会变慢,因为您正在初始化一个全新的MyResource而不是仅仅复制一个。

无论如何,它使得它HolderOfWrappers本身不是通用的,并且将填充anyWrappedItem与您传入的MyResource<Any>值相同的值。resource