Creating a Swift class conforms to a protocol that requires initialization

I have a protocol in Swift :

 protocol FooConvertible{ typealias FooType init(foo: FooType) } 

I can make Swift classes match it in the class definition:

 class Bar: FooConvertible { var baz: String = "" required init(foo: String){ baz = foo } } 

So far so good. However, the problem arises when I try to make the class compatible with it in the extension (with Cocoa classes, this is my only option, since I have no source):

 class Baz { var baz = "" } extension Baz: FooConvertible{ required convenience init(foo: String) { // Insists that this should be in the class definition baz = foo } } extension NSURL: FooConvertible{ required convenience init(foo: String) { // this also fails for the same reason } } 

This one was available in previous versions of the language.

What is the reason for its removal?

This would mean that all XXXLiteralConvertible Protocols are forbidden from Cocoa classes!

+6
source share
1 answer

If you are trying to create something like this:

 protocol FooConvertible : class { typealias FooType var baz : String { get set } // protocol extensions inits may need to know this init(foo: FooType) // this is your designated initializer } extension FooConvertible { // init(foo: String) { // self.init(foo: foo) // baz = foo // } // you can't do this because it could call it self recursively init(num: Int) { // this init will call your designated init and can instantiate correctly self.init(foo: "\(num)") } } class Baz { var baz = "" } class Bar: FooConvertible { var baz: String = "" required init(foo: String) { // designated initializer baz = foo } } 

Baz will now know about all inits FooConvertible . If so, I'm glad I can help. :)

+1
source

Source: https://habr.com/ru/post/978057/


All Articles