我试图实现一个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的扩展.
你可以用反思来做到这一点.不需要比你已经有更多的代码:
原文链接:https://www.f2er.com/swift/318814.htmlextension 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`