【问题标题】:Pass reference of static method to a function将静态方法的引用传递给函数
【发布时间】:2017-07-29 14:03:22
【问题描述】:

我在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 作为函数的参数传递,以便稍后在函数体中执行该函数。这可能吗?如何?我找不到办法。任何帮助表示赞赏

【问题讨论】:

  • 不相关,但在表达式上使用后缀 .self 只会返回该表达式;所以你可以说print(stored) 而不是print(stored.self)。

标签: swift function parameter-passing static-methods


【解决方案1】:
    printUsingReference(stored, "the")


static func printUsingReference(_ stored: (_ s: String) -> String, _ content: String) {
    print(stored(content))

}

【讨论】:

    【解决方案2】:

    你可以这样做:

    func Foo(param: (String) -> String) {
        print(param("Foo called"))
    }
    
    // Pass it your stored var
    Foo(param: stored)
    

    【讨论】:

    • 奇怪的是,我尝试过同样的方法,但没有成功,之后我尝试了你的代码,它成功了(可能是游乐场的一些缓存问题)
    【解决方案3】:

    为什么不使用闭包?存储其对变量的引用并从中获取值并传入您的函数。

    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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多