I am trying to create a utility to add closures as event handlers for UIControls though i am having a couple of issues, here is the code:
public func addCallBack(callback: Void -> Void, forControlEvents events: UIControlEvents)
{
var optClosureDict = objc_getAssociatedObject(self, &UIControlClosureDictKey) as? Dictionary<UInt, Set<ClosureWrapper>>
if optClosureDict == nil {
optClosureDict = Dictionary<UInt, Set<ClosureWrapper>>()
}
var closureDict = optClosureDict!
if closureDict[events.rawValue] == nil {
closureDict[events.rawValue] = Set<ClosureWrapper>()
}
var closures = closureDict[events.rawValue]!
let wrapper = ClosureWrapper(callback:callback)
addTarget(wrapper, action:"invoked", forControlEvents: events)
closures.insert(wrapper)
objc_setAssociatedObject(self, &UIControlClosureDictKey, optClosureDict!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
var res = objc_getAssociatedObject(self, &UIControlClosureDictKey) as? Dictionary<UInt, Set<ClosureWrapper>>
}
1) Both of the if statements seem really ugly where i call an API that returns an optional and if it is nil i want to overwrite it with some default, then i have to force unwrap it. Is there a more idiomatic 'Swifter' way of doing this?
2) Also when i create a closureDict that has one key value pair of int to a closure, then i store it using setAssociatedObject, what i then retrieve back in getAssociatedObject i get back a dictionary with 0 key value pairs. What is going on? This is a problem because my closureWrapper isnt being retained and the whole thing isnt working