如何将初始值设定项作为参数传递给函数?
class A {
var num: Int
init() {
num = 3
}
}
func f(# createA: () -> A) -> A {
return createA()
}
f(createA: A) // This does not work
更新
感谢The Paramagnetic Croissant的答案:
f(createA: { A() }) // Correct
但是如果初始化器有输入怎么办?
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
更新 好的,我想通了:
f(createA: { a in A(a: a) })
答案 0 :(得分:3)
这适用于Swift 2.0测试版(不知道1.2):
func f(createA createA: () -> A) -> A {
return createA()
}
f(createA: A.init)