0

So given the following code, how does one get a reference to a function that takes a parameter with a default value and invoke the reference with the default value?

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

I also tried the following

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

But that also does not work. Any ideas? I'd like to invoke fn2() and get the printed result "Done better"

nyteshade
  • 2,712
  • 1
  • 14
  • 9
  • `fn2` is a closure, and closures cannot have default values for their parameters. – Martin R Jul 14 '18 at 07:01
  • Possible duplicate of [Why Swift throws error when using optional param in closure func?](https://stackoverflow.com/q/45258621/1187415) – Martin R Jul 14 '18 at 07:10

1 Answers1

0

I think you already got what you wanted, a reference to that function.

Since the type is (String) -> Void, it expects String as an input. So you have to pass it to call.

pacification
  • 5,838
  • 4
  • 29
  • 51
Bista
  • 7,869
  • 3
  • 27
  • 55