Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift generic type that conform to protocol cannot be used to refer protocol?

import UIKit

protocol Identifiable
{
}

protocol Storage
{
    func test() -> Data<Identifiable>
}

class DiskStorage<T where T:Identifiable, T:NSCoding>:Storage
{
    func test() -> Data<Identifiable>
    {
       return Data<T>() //error: T is not identical to Identifiable
    }
}

class Data<T where T:Identifiable>
{

}

I thought it would be possible to use generic type that conform protocol in order to call method that reference that same protocol. How to cast it? Tried almost everything, nothing is working. Maybe I understand something wrong...

Any help on this one guys? Thanks a lot

like image 348
user1306602 Avatar asked Aug 20 '14 00:08

user1306602


1 Answers

try this

protocol Identifiable
{}

class Data<T where T:Identifiable>
{}

protocol Storage
{
    typealias Element : Identifiable
    func test() -> Data<Element>
}

class DiskStorage<T where T:Identifiable, T:NSCoding>:Storage
{
    func test() -> Data<T>
    {
       return Data<T>()
    }
}

// from REPL
 32> var s = DiskStorage<Foo>()
s: DiskStorage<Foo> = {}
 33> s.test()
$R0: Data<Foo> = {}

As I pointed out in this answer, Data<T> have no relationship to Data<Identifiable>. So you can't use Data<T> in place that expecting Data<Identifiable> and hence the compile error.

like image 78
Bryan Chen Avatar answered Oct 14 '22 09:10

Bryan Chen