skip to Main Content

Here’s a common variable, for example in network code.

private var callback: ((_ blah: String?) -> ())

Of course, you can’t do that because there’s no initializer.

This is easy enough

private var callback: ((_ blah: String?) -> ())?

then of course it’s just

private var callback: ((_ blah: String?) -> ())? = nil

for the initializer.

But how to initialize this?

private var callback: ((_ blah: String?) -> ())

So it’s going to be something like

private var callback: ((_ blah: String?) -> ()) = ( (_ String?){ return }() )

but I can not at all figure it out.

How to ?


Unrelated Here’s a common example, re the question asked about why callbacks are private

class SomeWorker {

  public func someLong(networkThing: String,
                      onMain: @escaping (_ foundIt: Blah?) -> () ) {
    
      callback = onMain
      loopForALongTimeDoingStuff( ... )
  }

  private var callback ...

2

Answers


  1. Chosen as BEST ANSWER

    Building on @burnsi' fantastic answer. It's possible the best idiom is

    private var callback: ((_ playableUrl: URL?) -> ()) = { _ in return }
    

    or even

    private var callback: ((_ playableUrl: URL?) -> ()) = { _ in return () }
    

  2. Try this syntax

    private var callback: ((_ blah: String?) -> ()) = { blah in }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search