[Possible bug] Initialising multiple instance variables from a closure


(Karl) #1

Currently you can initialise a class instance variable from a closure:

let textView : UITextView = {
    let t = UITextView()
    t.translatesAutoresizingMaskIntoConstraints = false
    t.autocapitalizationType = .none
    t.autocorrectionType = .no
    t.spellCheckingType = .no
    return t
  }()

However, it doesn’t seem to be possible to return and initialise multiple variables from a closure:

  let (toolbar : UIToolbar, aButton : UIBarButtonItem) = { // ERROR: Type of expression is ambiguous without more context
    let toolbar = UIToolbar()
    let aButton = UIBarButtonItem()
    return (toolbar, aButton)
  }()

Is this something which, in theory should be supported?

Thanks

Karl


(Karl) #2

Oh, I figured it out. The syntax is a bit strange, but after enough attempts I ended up at this:

  let (toolbar, aButton) : (UIToolbar, UIBarButtonItem) = {
    let toolbar = UIToolbar()
    let aButton = UIBarButtonItem()

    return (toolbar, aButton)
  }()

Seems to work ¯\_(ツ)_/¯

Karl

···

On 30 Jun 2016, at 02:57, Karl <raziel.im+swift-users@gmail.com> wrote:

Currently you can initialise a class instance variable from a closure:

let textView : UITextView = {
    let t = UITextView()
    t.translatesAutoresizingMaskIntoConstraints = false
    t.autocapitalizationType = .none
    t.autocorrectionType = .no
    t.spellCheckingType = .no
    return t
  }()

However, it doesn’t seem to be possible to return and initialise multiple variables from a closure:

  let (toolbar : UIToolbar, aButton : UIBarButtonItem) = { // ERROR: Type of expression is ambiguous without more context
    let toolbar = UIToolbar()
    let aButton = UIBarButtonItem()
    return (toolbar, aButton)
  }()

Is this something which, in theory should be supported?

Thanks

Karl