【发布时间】:2021-03-15 16:53:24
【问题描述】:
我知道闭包捕获给定环境中的值。那不是我的问题。我的问题是如何捕获闭包的返回值。例如,如果我使用闭包作为参数,例如:
func myClosure(yourAge x: Int, completion: (Int) -> String) {
if x == 4 {
completion(x)
}
}
然后说:
let answer = myClosure(yourAge: 4) { x in
return "You're just a baby"
}
警告是:
Constant 'answer' inferred to have type '()', which may be unexpected
我理解这个警告。几乎answer 根本不是答案。它将是Void 或()
现在,如果我让整个函数返回一个字符串,例如:
func myClosure(yourAge x: Int, completion: (Int) -> String) -> String {
completion(x)
}
那么我当然可以在属性中捕获结果:
let answer = myClosure(yourAge: 4) { x in
if x < 10 { return "You're just a baby"}
else {
return "You can play the game"
}
}
也许我只是在这里回答了我自己的问题,但是是否没有简单的方法可以将闭包的返回值放入属性中,或者我以非预期的方式使用它?
【问题讨论】: