Reputation: 4186
I need to define a dictionary of method calls in swift, effectively I want a list of function pointers based on passed in string, a pattern commonly seen in Python in lieu of switch statements. Perhaps I'm approaching this wrong and switch statement would be the recommended approach here but I wanted to move the setup logic into classes member variable declarations rather than having it reside in constructor for clarity. Here is what I currently tried and this should give you a rough idea of what I'm trying to achieve:
let typeMap: [String: (AnyObject) -> Void] = [
"UIButton.fgColor": {(value: UIColor) -> Void in UIButton.appearance().setTitleColor(value, forState: UIControlState.Normal) }
...
// hundreds more of these
]
Unfortunately I seem to be a getting an error stating that 'AnyObject' is not a subtype of 'UIColor'
, which I don't understand. I was under impression that all classes/objects inherit from AnyObject and UIColor is an object according to its manual. Clearly I'm missing something here, is my syntax wrong or my understanding in how the two are linked? Is there a better way to set this up?
Upvotes: 2
Views: 58
Reputation: 93161
You need to do the unwrapping inside the closure. Swift does not do automatic downcast to AnyObject
:
let typeMap: [String: (AnyObject) -> Void] = [
"UIButton.fgColor": {
if let color = $0 as? UIColor {
UIButton.appearance().setTitleColor(color, forState: UIControlState.Normal)
}
},
"anotherKey": ...
]
Upvotes: 1