I want to expand Dictionarywith keys String(JSON dictionaries) to allow signatures with anyone enumthat has a type RawValue String. The final goal will be several enumsthat can be used to index JSON dictionaries.
enum JSONKey: String {
case one, two, three
}
enum OtherJSONKey: String {
case a, b, c
}
if let one = jsonDictionary[.one] { }
if let b = jsonDictionary[.b] { }
But I can’t figure out how to implement this. I know that I need to expand Dictionary, but cannot define general extension restrictions or method extension restrictions.
My first idea was to try to add a general constraint to the index method. I don't think substring methods allow generics to be used.
extension Dictionary {
subscript<T: RawRepresentable>(key: T) -> Value? { }
}
, . , . , :
extension Dictionary where Key: RawRepresentable where RawValue == String {
subscript(key: Key) -> Value { }
}
extension Dictionary {
subscript<T: RawRepresentable where RawValue == String>(key: T) -> Value { }
}
Dictionary, , ?
, - , enum enums, . , , , . , , :
enum JSONKey: String {}
enum NumbersJSONKey: JSONKey {
case one, two, three
}
enum LettersJSONKey: JSONKey {
case a, b, c
}
protocol JSONKeys {}
enum NumbersJSONKey: JSONKey {
case one, two, three
}
enum LettersJSONKey: JSONKey {
case a, b, c
}
if let one = json[.one] { }
Update:
. , " ", .
extension Collection where Iterator.Element == (key: String, value: AnyObject) {
subscript(key: CustomStringConvertible) -> AnyObject? {
guard let i = index(where: { $0.key == key.description }) else { return nil }
return self[i].value
}
}
@titaniumdecoy , , - - .