Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Swift class conform to a protocol that requires an init

I have the following protocol in Swift:

protocol FooConvertible{
    typealias FooType

    init(foo: FooType)
}

I can make Swift classes conform to 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 a class conform to it in an extension (With Cocoa classes, it's my only option, as I don't have the 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 used to be possible, in previous versions of the language

What's the reason it was removed?

That would mean that all the XXXLiteralConvertible Protocols are banned from Cocoa classes!

like image 498
cfischer Avatar asked Nov 11 '14 23:11

cfischer


1 Answers

Any chance 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 of FooConvertible. If so, I'm glad I could help. :)

like image 95
DevAndArtist Avatar answered Oct 04 '22 22:10

DevAndArtist