Swift - 具有实现通用协议的值的Typealias字典

Ryn*_*eow 5 protocols ios swift

我想输入一个String键的字典和实现Equatable协议的对象/结构的值.所以我写了这行代码,但它给了我错误,我不知道如何继续修复.

typealias Storage = [String: Equatable]
Run Code Online (Sandbox Code Playgroud)

我想使用类型[String:Equatable]作为协议中的变量,例如:

protocol StorageModel {
    var storage: Storage { get set }
    init(storage: Storage)
}
Run Code Online (Sandbox Code Playgroud)

错误:

协议'Equatable'只能用作通用约束,因为它具有Self或相关类型要求

在此输入图像描述 谁有人建议解决方案?

Dav*_*rry 5

一般来说,协议标签不是必需的,协议名称是一流的类型名称,可以直接使用:

typealias Storage = [String:Equatable]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,错误告诉你的是因为Equatable包含func == (lhs:Self, rhs:Self) -> Bool并且具体地说lhs:Self,除了作为泛型的约束之外,不能使用Equatable:

class Generic<T:Equatable> { ... }
Run Code Online (Sandbox Code Playgroud)

如果没有关于您要实现的目标以及如何使用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]()


}
Run Code Online (Sandbox Code Playgroud)

另一种可能性是使用泛型而不是协议:

class StorageModel <T:Equatable> {
    var storage: [String:T]

    init(storage:[String:T]) {
        self.storage = storage
    }
}
Run Code Online (Sandbox Code Playgroud)

从那里你需要做一些研究,深入研究Swift手册,做一些谷歌搜索,看看是什么解决了你的问题.