swift 中具有不同输入的闭包字典

dictionary of closures with varying inputs in swift

我需要在 swift 中定义一个方法调用字典,实际上我想要一个基于传入字符串的函数指针列表,这是 Python 中常见的一种模式,用于代替 switch 语句.也许我正在接近这个错误,switch 语句将是这里推荐的方法,但我想将设置逻辑移动到 类 成员变量声明中,而不是为了清晰起见将其驻留在构造函数中。这是我目前尝试的方法,这应该让您大致了解我要实现的目标:

let typeMap: [String: (AnyObject) -> Void] = [
    "UIButton.fgColor": {(value: UIColor) -> Void in UIButton.appearance().setTitleColor(value, forState: UIControlState.Normal) }
    ...
    // hundreds more of these
]

不幸的是,我似乎收到一条错误消息,指出 'AnyObject' is not a subtype of 'UIColor',我不明白。我的印象是所有 classes/objects 都继承自 AnyObject 并且 UIColor 根据其手册是一个对象。显然我在这里遗漏了一些东西,是我的语法错误还是我对两者如何联系的理解?有没有更好的设置方法?

您需要在闭包内展开。 Swift 不会自动向下转换为 AnyObject:

let typeMap: [String: (AnyObject) -> Void] = [
    "UIButton.fgColor": {
        if let color = [=10=] as? UIColor {
            UIButton.appearance().setTitleColor(color, forState: UIControlState.Normal)
        }
    },
    "anotherKey": ...
]