EN VI

Swift - Generically initialize instance of a class that conforms to protocol?

2024-03-14 04:00:11
How to Swift - Generically initialize instance of a class that conforms to protocol

Have:

protocol MyProtocol {
   var value: Int { get set }
}

class Foo: MyProtocol {
   var value: Int
}

class Bar: MyProtocol {
   var value: Int
}

Want:

function generate(value: _) that infers the protocol-conforming class for instantiation:

let foo: Foo = generate(value: 1)
let bar: Bar = generate(value: 2)

Solution:

The code doesn't compile because the init methods in the classes are missing

Add an init requirement to the protocol

protocol MyProtocol {
    var value: Int { get set }
    init(value: Int)
}

and this init method in both classes

required init(value: Int) {
    self.value = value
}

Now you can create a generic generate method

func generate<T: MyProtocol>(value: Int) -> T {
    T(value: value)
} 
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login