简体   繁体   English

Swift:Dictionary by Dictionary的约束扩展

[英]Swift: Constrained extension on Dictionary by Element

I want to create an extension on Dictionary that only affects dictionaries with type [String:AnyObject], which is the data type returned from parsed JSON dictionaries. 我想在Dictionary上创建一个扩展,它只影响类型为[String:AnyObject]的字典,这是从解析的JSON字典返回的数据类型。 Here's how I set it up: 这是我如何设置它:

typealias JSONDictionary = [String : AnyObject]
extension Dictionary where Element:JSONDictionary {
    // Some extra methods that are only valid for this type of dictionary.
}

Xcode is generating an error on Element , saying it's an undeclared type. Xcode在Element上生成错误,称它是未声明的类型。 However, the first line of the definition of Dictionary is a typealias declaring Element. 但是,Dictionary定义的第一行是声明Element的typealias。 What am I doing wrong here? 我在这做错了什么?

Element is a tuple: Element是一个元组:

typealias Element = (Key, Value)

That cannot match the type you're trying to compare it to (a Dictionary). 这与您尝试将其与(词典)进行比较的类型无法匹配。 You can't even say something like where Element:(String, AnyObject) because tuples don't subtype that way. 你甚至不能说像where Element:(String, AnyObject)因为元组不是那种子类型。 For example, consider: 例如,考虑:

var x: (CustomStringConvertible, CustomStringConvertible) = (1,1)
var y: (Int, Int) = (1,1)
x = y // Cannot express tuple conversion '(Int, Int)' to ('CustomStringConvertible', 'CustomStringConvertible')

Compare: 相比:

var x1:CustomStringConvertible = 1
var y1:Int = 1
x1 = y1 // No problem

I suspect you get "undeclared type" is because Element is no longer an unbound type parameter, it's a bound type parameter. 我怀疑你得到“未声明类型”是因为Element不再是未绑定的类型参数,它是一个绑定类型参数。 Dictionary is conforming to SequenceType here. Dictionary符合SequenceType So you can't parameterize on it (at least not in one step; you have to chase it through another layer of type parameters to discover it's "ultimately" unbound). 所以你不能对它进行参数化(至少不是一步;你必须通过另一层类型参数来追逐它以发现它“最终”未绑定)。 That seems a bad error message, but I suspect it bubbles out of "undeclared type out of the list of types that could possibly be used here." 这似乎是一个错误的错误消息,但我怀疑它出现了“可能在这里使用的类型列表中未声明的类型”。 I think that's worth opening a radar on for a better error message. 我认为值得打开雷​​达以获得更好的错误信息。

Instead, I think you mean this: 相反,我认为你的意思是:

extension Dictionary where Key: String, Value: AnyObject { }

EDIT for Swift 2: 编辑Swift 2:

This is no longer legal Swift. 这不再是合法的斯威夫特。 You can only constrain based on protocols. 您只能基于协议进行约束。 The equivalent code would be: 等效代码是:

protocol JSONKey {
    func toString() -> String
}
extension String: JSONKey {
    func toString() -> String { return self }
}

extension Dictionary where Key: JSONKey, Value: AnyObject { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM