Swift:使用通配符作为泛型类型参数

Ann*_*son 7 generics wildcard swift

我想在Dictionary中存储从泛型类派生的类的实例; 也就是说,Dictionary应该存储从这个泛型派生的任何类的实例.

像这样的东西:

class ParentClass {}
class ChildClass: ParentClass {}

class GenericClass<T: ParentClass> {
    var foo:T?
}

typealias DerivedClass = GenericClass<ChildClass>

class TestGenerics {

    var dict: Dictionary<String, GenericClass<**what goes here??**>> = [:]

    func test() {
        var derivedClassInstance = DerivedClass()
        dict.updateValue(derivedClassInstance, forKey: "name")
    }
}
Run Code Online (Sandbox Code Playgroud)

这在Java中相当简单:

public class TestGenericsOuter {

    class ParentClass {}
    class ChildClass extends ParentClass {}

    class GenericClass<T extends ParentClass> {
        T foo;
    }

    class DerivedClass extends GenericClass<ChildClass> {}

    class TestGenerics {

        Dictionary<String, GenericClass<? extends ParentClass>> dict;

        void test() {
            DerivedClass derivedClassInstance = new DerivedClass();
            dict.put("name", derivedClassInstance);

        }
    }

}
Run Code Online (Sandbox Code Playgroud)

在Swift中这样的事情可能吗?我实现这一点的唯一方法是创建一个以"Any"作为值类型的Dictionary.但是,我失去了一些类型的安全性,所以如果可能的话,我想避免这种解决方案.

ric*_*ter -1

您需要参数化包含要泛型化的任何引用的类型,并在那里使用类型约束。此外,类型别名与参数化类型的约束相关,因此它位于该类型内部。

class ParentClass {}
class ChildClass: ParentClass {}

class GenericClass<T: ParentClass> {
    var foo:T?
}


class TestGenerics<T: ParentClass> {
    typealias DerivedClass = GenericClass<T>

    var dict: Dictionary<String, GenericClass<T>> = [:]

    func test() {
        var derivedClassInstance = DerivedClass()
        dict.updateValue(derivedClassInstance, forKey: "name")
    }
}

let blah = TestGenerics<ChildClass>()
let baz = GenericClass<ChildClass>()
baz.foo = ChildClass()
blah.dict = ["a":baz]
Run Code Online (Sandbox Code Playgroud)