Swift Dictionary - Typealias with a value implementing the common protocol

I want to introduce a dictionary for string keys and values ​​of objects / structures that implement the Equatable protocol. So I wrote this line of code, but it gave me an error that I did not know how to fix it.

typealias Storage = [String: Equatable] 

I want to use the type [String: Equatable] as a variable in the protocol, for example:

 protocol StorageModel { var storage: Storage { get set } init(storage: Storage) } 

Error:

The Equatable protocol can only be used as a general restriction because it has its own or related requirements like

enter image description here Can anyone suggest a solution?

+5
source share
1 answer

In general, a protocol tag is not required; protocol names are first-class type names and can be used directly:

 typealias Storage = [String:Equatable] 

In this case, what the error tells you is that, since Equatable includes func == (lhs:Self, rhs:Self) -> Bool and specifically lhs:Self , Equatable cannot be used, except as a general restriction:

 class Generic<T:Equatable> { ... } 

Without additional information about what you are trying to achieve and how you are trying to use StorageModel, I can come up with the following:

 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 common protocol instead of a protocol:

 class StorageModel <T:Equatable> { var storage: [String:T] init(storage:[String:T]) { self.storage = storage } } 

From there, you will need to do some research, look into the Swift manual, do some search queries and see what solves your problem.

+5
source

Source: https://habr.com/ru/post/1202985/


All Articles