【问题标题】:Getting a reference to an instance variable with a default parameter in Swift在 Swift 中使用默认参数获取对实例变量的引用
【发布时间】:2018-12-22 11:24:56
【问题描述】:

那么给定下面的代码,如何获取一个函数的引用,该函数接受一个带有默认值的参数并调用带有默认值的引用?

class Test {
  func doIt() { print("Done") }
  func doIt(_ adjective: String = "better") {
    print("Done \(adjective)")
  }
}


let t = Test()
let fn1 = t.doIt as () -> Void
let fn2 = t.doIt as (String) -> Void

fn1() // Works
fn2() // Does not work; requires parameter

我也尝试了以下

let fn2 = t.doIt as (String?) -> Void

但这也行不通。有任何想法吗?我想调用fn2() 并得到打印结果"Done better"

【问题讨论】:

标签: swift function default-parameters


【解决方案1】:

我想你已经得到了你想要的,对该函数的引用。

由于类型是(String) -> Void,它需要String 作为输入。所以你必须通过它来调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2013-06-04
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    相关资源
    最近更新 更多