Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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, e.g:

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

enter image description here Can anyone suggest a solution?

like image 933
Ryne Cheow Avatar asked Sep 19 '14 15:09

Ryne Cheow


1 Answers

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:

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:

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.

like image 142
David Berry Avatar answered Oct 15 '22 05:10

David Berry