对关联类型有约束的通用下标导致 "Cannot subscript a value of type..."
Generic subscript with constraints on associated type leads to "Cannot subscript a value of type..."
使用 Swift 4.2,我正在尝试编写一个通用系统来摆脱字符串作为字典的键,而改用枚举。
这是我带来的:
extension Dictionary where Key == String {
subscript<T : RawRepresentable>(key: T) -> Value? where T.RawValue == String {
get { return self[key.rawValue] }
set { self[key.rawValue] = newValue }
}
}
这会编译,并且注定要将任何具有 String
原始值的 RawRepresentable
类型作为每个 Dictionary
和 String
作为键的下标的键。
不幸的是,当我执行以下操作时,它没有编译:
enum MovieKey: String {
case movieId = "movie_id"
case movies = "movies"
}
var dic = [String:String]()
dic[key: MovieKey.movieId] = "abc123" // error
我得到以下编译错误:Cannot subscript a value of type '[String : String]' with an index of type '(key: MovieKey)'
除非我弄错了,dic
是一个 Dictionary
,以 String
为键,MovieKey
是 RawRepresentable
,原始值是String
输入...
如果有人能解释我做错了什么,在此先感谢。
问题是您没有正确使用下标。您不应该为下标调用提供任何参数标签,只需提供 enum
值。
dic[MovieKey.movieId] = "abc123"
编译得很好。
使用 Swift 4.2,我正在尝试编写一个通用系统来摆脱字符串作为字典的键,而改用枚举。
这是我带来的:
extension Dictionary where Key == String {
subscript<T : RawRepresentable>(key: T) -> Value? where T.RawValue == String {
get { return self[key.rawValue] }
set { self[key.rawValue] = newValue }
}
}
这会编译,并且注定要将任何具有 String
原始值的 RawRepresentable
类型作为每个 Dictionary
和 String
作为键的下标的键。
不幸的是,当我执行以下操作时,它没有编译:
enum MovieKey: String {
case movieId = "movie_id"
case movies = "movies"
}
var dic = [String:String]()
dic[key: MovieKey.movieId] = "abc123" // error
我得到以下编译错误:Cannot subscript a value of type '[String : String]' with an index of type '(key: MovieKey)'
除非我弄错了,dic
是一个 Dictionary
,以 String
为键,MovieKey
是 RawRepresentable
,原始值是String
输入...
如果有人能解释我做错了什么,在此先感谢。
问题是您没有正确使用下标。您不应该为下标调用提供任何参数标签,只需提供 enum
值。
dic[MovieKey.movieId] = "abc123"
编译得很好。