[英]Swift - Typealias dictionary with value that implements a generic protocol
I want to typealias a dictionary of String keys and values of objects/structs that implements the Equatable protocol. 我想将实现Equatable协议的String键和对象/结构的值的字典类型化。 So I wrote this line of code but it gave me error that I didn't know how to go on to fix.
所以我写了这行代码,但它给了我一个我不知道如何继续修复的错误。
typealias Storage = [String: Equatable]
I want to use the type [String: Equatable] as a variable in a protocol, eg: 我想将[String:Equatable]类型用作协议中的变量,例如:
protocol StorageModel {
var storage: Storage { get set }
init(storage: Storage)
}
Error: 错误:
Protocol 'Equatable' can only be used as a generic constraint because it has Self or associated type requirements
协议“ Equatable”只能用作通用约束,因为它具有“自身”或相关类型要求
Can anyone suggest a solution?
谁能提出解决方案?
Generally speaking, the protocol tag isn't required, protocol names are first-class type names and can be used directly: 一般来说,协议标签不是必需的,协议名称是一流的类型名称,可以直接使用:
typealias Storage = [String:Equatable]
In this case, what the error is telling you is that because Equatable includes func == (lhs:Self, rhs:Self) -> Bool
and specifically lhs:Self
, Equatable can't be used except as a constraint on a generic: 在这种情况下,错误告诉您的是,因为Equatable包含
func == (lhs:Self, rhs:Self) -> Bool
,尤其是lhs:Self
,所以Equatable不能用作对通用的约束:
class Generic<T:Equatable> { ... }
Without more details about what you're trying to achieve and how you're trying to use StorageModel, the best I can come up with is: 在没有更多关于您要实现的目标以及如何使用StorageModel的详细信息的情况下,我能想到的最好的方法是:
protocol Matches {
typealias T
func matches(t:T) -> Bool
}
protocol StorageModel {
typealias T
var storage: [String:T] { get set }
init(storage:[String:T])
}
extension Int : Matches {
func matches(target:Int) -> Bool {
return self == target
}
}
class MyClass <T:Matches> {
var model = [String:T]()
}
Another possibility is to use a generic instead of a protocol: 另一种可能性是使用通用而不是协议:
class StorageModel <T:Equatable> {
var storage: [String:T]
init(storage:[String:T]) {
self.storage = storage
}
}
From there you'll need to do some research, dig into the Swift manual, do some googling and see what solves your problem. 从那里开始,您需要做一些研究,深入研究Swift手册,进行谷歌搜索,看看解决问题的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.