Skip to content

Instantly share code, notes, and snippets.

@waynebloss
Created March 10, 2016 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waynebloss/c682c8949a89ddbbe443 to your computer and use it in GitHub Desktop.
Save waynebloss/c682c8949a89ddbbe443 to your computer and use it in GitHub Desktop.
How do I extend this dictionary?
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
@waynebloss
Copy link
Author

When I write the extension like this:

public extension Dictionary where
    Key: StringLiteralConvertible, Value: ComponentObject {
    public func getByPath(path: Key) -> Value? {
        // TODO: Split the path and descend into components...
        return self[path]
    }
}

I get an error when I call getByPath:

let c2 = d.getByPath("other2")! // Error: Using ComponentObject as a concrete type conforming to protocol 'ComponentObject' is not supported.

@waynebloss
Copy link
Author

When I make ComponentObject a class instead of a protocol everything works.

However, Apple states that "Because it is a type, you can use a protocol in many places where other types are allowed" here and shows examples of using protocols as the value in a collection here. So, what am I doing wrong?

@waynebloss
Copy link
Author

The answers were found and documented over at StackOverflow.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment