How can I use a function with default parameters for protocol conformance?

I need to do something like this (simplified for clarity):

protocol Initable {
    init()
}
struct Foo : Initable {
    var bar: String
    init(bar: String = "Foobar") {
        self.bar = bar
    }
}
let foo = Foo()

but the compiler complains that Foo doesn't conform to the protocol, even though "let foo = Foo()" is perfectly valid code. In fact, I intend to call the function using the default parameters anyway... In my actual code there are several parameters with the defaults set to __FILE__, __FUNCTION__, __LINE__, and __COLUMN__ so that I can capture some metadata.


Anyone know a way to force the compiler to use a specific function for protocol conformance?

Replies

Your Foo init signature doesn't match the Initable init signature. The protocol defines an init that takes no parameters, and Foo doesn't have an init that takes no parameters. Change the protocol to:

protocol Initable {
    init(bar: String)
}

Or, leave the protocol as it is and give bar an initial value that you change later (requres foo to be var instead of let):

struct Foo : Initable { 
    var bar: String = "Foobar"
    init() { 
          // other init stuff
    } 
}
var foo = Foo()
foo.bar = "Something Else"

Nuts, I'll have to add "fluff" initializers to everything then. I can't assign a temporary value to bar because I'm parsing the source code to get bar's value, and the only way to automatically get the relevant text (that I know of) is to pass in __FILE__ and __LINE__ as default parameters, and read/parse the file in the initializer.


I guess Swift requires "literal" conformance rather than "semantic" conformance.