简体   繁体   中英

Generic Constraints and Initializer Inheritance in Swift

I am trying to call an initializer required by protocol A on a type that both conforms to A and is a subclass of C .

All is fine and good if C is a base class. But as soon as C subclasses another class, say B , it breaks.

Here's what I am talking about:

protocol A {
    init(foo: String)
}

class B {
    init() {}
}

class C: B {}

func makeSomething<T: A>() -> T where T: B {
    return T(foo: "Hi")
}

That works. But if I change where T: B to where T: C , I get the following error: argument passed to call that takes no arguments . It will only allow me to call B s init .

Why can't I call this initializer? I understand that the super class has its own designated initializers that must be called. But that will be enforced when someone actually writes the class that subclasses B and conforms to A . (Eg implementing init(Foo: String) and calling super.init(bar: Int) inside).

Any help here would be greatly appreciated. Thanks!

Swift provides a default initializer for your base class if it has all properties initialized but not incase of Generics because Swift may think its properties has not been initialized.

So when you constraint your return type as

func makeSomething<T: A>() -> T where T: C

It requires initialization for class C as Swift cannot provide a default initializer.But if your remove the where clause everything works fine

func makeSomething<T: A>() -> T {
    return T(foo:"string")
}

If you want to return return T(foo: "Hi") :

You are getting error because class C doesn't have initializer that accepts init(foo: String)

Change your class C as

class C: A {
    required init(foo: String) {

    }
}

which provides at least one initializer that accepts the argument type.

So, remember if you don't subclass There is already one initializer doing your job and you dont get error.

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