Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'let' property may not be initialized directly; use "self.init(...)" or "self = ..." instead

I want to try to write a default init in a protocol extension, so I did this:

protocol P {
    var data: [AnyHashable: Any] { get }
    init(_ s: String)
}

extension P {
    init(_ s: String) {
        self.data = ["s": s]
    }
}

But I'm getting this error:

'let' property 'data' may not be initialized directly; use "self.init(...)" or "self = ..." instead

I have no idea what it means. Thanks for your help!

like image 559
Denis Avatar asked Jan 14 '19 12:01

Denis


1 Answers

The error says that the variable cannot be initialized in the protocol extension because it's declared as constant { get }

But even if you declare the variable { get set } you can't use the init method anyway without a constraint to a concrete type or an associated type.

like image 104
vadian Avatar answered Sep 21 '22 21:09

vadian