简体   繁体   中英

How to use initializer as Closure in Swift

How to pass an initializer as a parameter to a function?

class A {
    var num: Int
    init() {
        num = 3
    }
}

func f(# createA: () -> A) -> A {

   return createA()
}


f(createA: A)   // This does not work

Update

Thank you for The Paramagnetic Croissant's answer:

f(createA: { A() }) // Correct

But what if the initializer has an input?

class A {
    var num: Int
    init(a : Int) {
        num = 3
    }
}
func f(# createA: (a: Int) -> A) -> A {

    return createA(a: 1)
}

let a = f(createA: {A(a: Int)}) // Wrong

Update OK I figured out:

f(createA: { a in A(a: a) })

This works in Swift 2.0 beta (don't know about 1.2):

func f(createA createA: () -> A) -> A {
    return createA()
}


f(createA: A.init)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM