Hi,
I have been trying to prove a concept in Swift that I implemented in another language. I thought it would be easy is Swift, but it doesn't seem to work.
My playground code is below. When I call the 2 btn.click() functions at the end it get
The caption is Say hello
Can't find proc for Say hello
The proc was just called
The caption is Greet Veronica
Can't find proc for Greet Veronica
The proc was just called
I was hoping that sayHello would be called and then the closure to greet Veronica.
Can anyone see what coud be going wrong here?
TIA
Mark
import UIKit
print("\nTesting assignment of functions\n")
typealias Proc = () -> ()
typealias Event = AnyObject -> ()
class Button {
var caption: String
var onClick: Event?
init(caption: String, onClick: Event? = nil) {
self.caption = caption
self.onClick = onClick
}
func click() {
onClick?(self)
}
}
func sayHello() { print("Hello") }
func greet(name: String) { print("Hello", name) }
let sh = "Say hello"
let gv = "Greet Veronica"
struct Form {
var commands = [String: Proc]()
let btn1 = Button(caption: sh)
let btn2 = Button(caption: gv)
func stdBtnClick(sender: AnyObject) {
guard let button = sender as? Button else { return }
print("\nThe caption is", button.caption)
if let proc = commands[button.caption] {
proc()
} else {
print("Can't find proc for", button.caption)
}
print("The proc was just called\n")
}
init() {
btn1.onClick = stdBtnClick
btn2.onClick = stdBtnClick
commands.updateValue(sayHello, forKey: sh)
commands.updateValue( { greet("Veronica") }, forKey: gv)
print("Commands =", commands)
}
}
let form = Form()
form.btn1.click()
form.btn2.click()