我在Swift
中找到了你可以存储静态方法的引用而不实际执行它:
class StringMama {
static func returnString(s:String)->String {
return s
}
}
var stored = StringMama.returnString
print(stored.self) // (Function)
print(stored(s:"Hello!")) // for some reason it doesn't work
print(stored("Hello!")) // it works
现在,我希望在函数体中传递stored
作为函数的参数,以便稍后执行该函数。这可能吗?怎么样?我找不到办法。任何帮助表示赞赏
答案 0 :(得分:1)
printUsingReference(stored, "the")
static func printUsingReference(_ stored: (_ s: String) -> String, _ content: String) {
print(stored(content))
}
答案 1 :(得分:1)
你可以这样做:
func Foo(param: (String) -> String) {
print(param("Foo called"))
}
// Pass it your stored var
Foo(param: stored)
答案 2 :(得分:1)
为什么不使用封口?存储对变量的引用并从中获取值并传入函数。
var someValue: (String) -> String = { stringValue in
return stringValue
}
func someFunction(value: String) {
print(value)
}
//Now pass closure reference into one variable
let value = someValue
//Using in that function like below.
someFunction(value: value("test"))