我在Swift 2中有一个字典[String: ComponentObject]()
,我无法为此类型编写扩展名。但是,当我ComponentObject
class
而不是protocol
时,它会按预期工作。
这是一个演示字典基本设置的游乐场:
import Foundation
protocol ComponentObject {
var name: String { get }
}
private var _idPrev = 0;
private func defaultName(baseName: String) -> String {
return baseName + String(++_idPrev)
}
class Thing : ComponentObject {
let name: String
init(name: String? = nil) {
self.name = name ?? defaultName("thing")
}
}
class OtherThing : ComponentObject {
let name: String
init(name: String? = nil) {
self.name = name ?? defaultName("other")
}
}
let w = Thing()
w.name
let m = OtherThing()
m.name
var d = [String: ComponentObject]()
d[w.name] = w
d[m.name] = m
let c = d["other2"]!
c.name
当我像这样编写扩展名时:
public extension Dictionary where
Key: StringLiteralConvertible, Value: ComponentObject {
public func getByPath(path: Key) -> Value? {
// TODO: Some other stuff...
return self[path]
}
}
调用getByPath时出错:
let c2 = d.getByPath("other2")!
// Error: Using ComponentObject as a concrete type conforming to protocol
// 'ComponentObject' is not supported.
Apple声称“因为它是一种类型,您可以在允许其他类型的许多地方使用协议”here,并显示使用协议作为集合here中的值的示例。那么,我做错了什么?