0

I have view controller A that presents view controller B as a popover. What I'm trying to do is to get a value that's set in view controller B, back in view controller A.

My thought is that I would accomplish this by passing in a closure that takes a parameter and having view controller B calling that with the parameter.

So, in VC A, I have:

func update(val:String) {
}

Then, when I create VC B, I tried:

bVC.notifier = update

but I'm getting error:

Cannot assign value of type '(String, String) -> ()' to type '() -> {}'

Then, in view controller B:

public var notifier = {}

then I'm not really sure how to call it.

I've read through: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94 but don't think it covered this situation very well.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Thom
  • 14,013
  • 25
  • 105
  • 185
  • *Remark:* you might want to check other mechanisms for achieving such a functionality, check [this answer](https://stackoverflow.com/questions/40501780/examples-of-delegates-in-swift-3/40503024#40503024) (Alternatives) – Ahmad F Mar 14 '17 at 12:36

1 Answers1

2

If you want to do it this way, here's an example put together in a playground. It uses simple objects rather than view controllers, but it should show the syntax required.

class A {
    func doSomething() {
        let myB = B()
        myB.notifier = { (s1, s2) in
            print("\(s1) : \(s2)")
        }
        myB.give()
    }
}

class B {
    typealias ReturnRoutine = (String, String) -> ()
    var notifier: ReturnRoutine?

    func give() {
        if let notifier = notifier {
            notifier("First", "Second")
        }
    }
}

let myA = A()
myA.doSomething()
Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
  • I can use this and thank you. You did not specify using an existing function as the closure, though. – Thom Mar 14 '17 at 15:45
  • 1
    I believe it's a direct substitution as long as your function has a compatible signature, `func f(one: String, two: String)` in this case. – Phillip Mills Mar 14 '17 at 16:06