[swift-users] Capturing references to initializers?

Pierre Monod-Broca pierre at monod-broca.fr
Fri Dec 11 01:19:36 CST 2015


Hi,

I had the same problem with delegate methods (they all had the same prefix). I used lambda as a workaround, but I agree it is less elegant :

let b: = { Foo(customNumber: $0) }
let c: = { Foo(numberToInc: $0) }


Pierre

> Le 10 déc. 2015 à 23:41, Austin Zheng via swift-users <swift-users at swift.org> a écrit :
> 
> 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
>  _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151211/8b54a173/attachment.html>


More information about the swift-users mailing list