将静态方法的引用传递给函数
Pass reference of static method to a function
我在 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
作为函数的参数传递,以便稍后在函数体中执行该函数。这可能吗?如何?我找不到办法。感谢任何帮助
printUsingReference(stored, "the")
static func printUsingReference(_ stored: (_ s: String) -> String, _ content: String) {
print(stored(content))
}
您可以这样做:
func Foo(param: (String) -> String) {
print(param("Foo called"))
}
// Pass it your stored var
Foo(param: stored)
为什么不使用闭包?存储它对变量的引用并从中获取值并传入您的函数。
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"))
我在 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
作为函数的参数传递,以便稍后在函数体中执行该函数。这可能吗?如何?我找不到办法。感谢任何帮助
printUsingReference(stored, "the")
static func printUsingReference(_ stored: (_ s: String) -> String, _ content: String) {
print(stored(content))
}
您可以这样做:
func Foo(param: (String) -> String) {
print(param("Foo called"))
}
// Pass it your stored var
Foo(param: stored)
为什么不使用闭包?存储它对变量的引用并从中获取值并传入您的函数。
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"))