如何捕获闭包的 return 值
How to capture the return value of a closure
我知道闭包捕获给定环境中的值。那不是我的问题。我的问题是如何捕获闭包的 return 值。例如,如果我使用闭包作为参数,例如:
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
或 ()
现在,如果我将整个函数 return 设为一个字符串,例如:
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"
}
}
也许我只是在这里回答了我自己的问题,但是是否没有简单的方法可以将闭包的 return 值放入 属性 中,或者我以无意的方式使用它?
如果你只想用闭包(而不是接受闭包的函数)来做到这一点,你可以这样做:
let myClosure: (Int) -> String = { age in
if age < 10 {
return "You're just a baby"
}
else {
return "You can play the game"
}
}
let answer = myClosure(4) // "You're just a baby"
我知道闭包捕获给定环境中的值。那不是我的问题。我的问题是如何捕获闭包的 return 值。例如,如果我使用闭包作为参数,例如:
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
或 ()
现在,如果我将整个函数 return 设为一个字符串,例如:
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"
}
}
也许我只是在这里回答了我自己的问题,但是是否没有简单的方法可以将闭包的 return 值放入 属性 中,或者我以无意的方式使用它?
如果你只想用闭包(而不是接受闭包的函数)来做到这一点,你可以这样做:
let myClosure: (Int) -> String = { age in
if age < 10 {
return "You're just a baby"
}
else {
return "You can play the game"
}
}
let answer = myClosure(4) // "You're just a baby"