如何编写处理可选值的Dictionary扩展

时间:2015-01-03 16:22:23

标签: swift swift-dictionary

我正在尝试实现Dictionary扩展,我想处理可选值。但无论我做什么,如果我在[String: String?]字典上使用我的方法,它都无法选择性地绑定该值。如何编写一个优雅处理可选值的字典的扩展名?


考虑以下扩展名:

extension Dictionary {
    func someMethod() {
        for (key, value) in self {
            if let valueString = value as? String {
                println("  \(key) = \(valueString)")
            } else {
                println("  \(key) = \(value) cannot be cast to `String`")
            }
        }
    }
}

请考虑以下代码:

let dictionary: [String: AnyObject?] = ["foo": "bar"]
dictionary.someMethod()

好奇地报道

foo = Optional(bar) cannot be cast to `String`

我可以编写一个非扩展方法来处理带有可选值的字典参数,但是不知道如何将它作为Dictionary的扩展来处理。

2 个答案:

答案 0 :(得分:4)

你可以用反射做到这一点。不需要比现有代码多得多的代码:

extension Dictionary
{
    func someMethod()
    {
        for (key, value) in self
        {
            var valueRef = _reflect(value)

            while valueRef.disposition == .Optional && valueRef.count > 0 && valueRef[0].0 == "Some"
            {
                valueRef = valueRef[0].1
            }

            if let valueString: String = valueRef.value as? String
            {
                print("  \(key) = \(valueString)")
            }
            else
            {
                print("  \(key) = \(value) cannot be cast to `String`")
            }
        }
    }
}

let dictionary: [String : AnyObject?] = ["foo" : "bar"]
dictionary.someMethod()

返回

foo = bar

let dictionary: [String : AnyObject?] = ["foo" : nil]
dictionary.someMethod()

返回

foo = nil cannot be cast to `String`

let dictionary: [String : AnyObject?] = ["foo" : UIViewController()]
dictionary.someMethod()

返回

foo = Optional(<UIViewController: 0x7fee7e819870>) cannot be cast to `String`

答案 1 :(得分:0)

插入':String?'时我没有遇到任何问题紧跟在valueString之后,如下所示:

extension Dictionary {
    func someMethod() -> Bool {
        for (key, value) in self {
            if let valueString:String? = value as? String {
                println("  \(key) = \(valueString)")
            } else {
                println("  \(key) = \(value) cannot be cast to `String`")
                return false
            }
        }
        return true
    }
}

func doSomething() {
    let dictionary: [String: AnyObject?] = ["foo": "bar"]
    if dictionary.someMethod() {
        println("no problems")
    } else {
        println("casting issues")
    }
}