[swift-users] Capturing references to initializers?

Austin Zheng austinzheng at gmail.com
Thu Dec 10 16:41:39 CST 2015


Hello Swift users,

I have a question about capturing references to initializers. You can do
the following right now:

struct Foo {
    let number : Int
    // This type has a single initializer
    init() {
        number = 10
    }
}

let a  = Foo.init  // a's type: () -> Foo

So far so good. Now, let's add in a second initializer:

extension Foo {
    init(customNumber: Int) {
        number = customNumber
    }
}

Now, if you want to capture a reference to one of the initializers, you can
annotate the variable with the explicit function type:

let a : () -> Foo = Foo.init
let b : Int -> Foo = Foo.init

My question involves the case where you have multiple initializers that
take the same arguments and types. How would you capture initializers then?

extension Foo {
    init(numberToInc: Int) {
        number = numberToInc + 1
    }
}

How do I capture a reference to the numberToInc: initializer, versus the
customNumber: initializer?

Best regards,
Austin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151210/b2acf928/attachment.html>


More information about the swift-users mailing list