Protocol Swift Type Cannot Be Used to Transfer 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 a generic protocol type to invoke a method that references the same protocol. How to do it? I tried almost everything, nothing works. Maybe I understand something is wrong ...

Any help on this guy? Thank you very much

+6
source share
1 answer

try it

 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> not related to Data<Identifiable> . Thus, you cannot use Data<T> where you expect Data<Identifiable> and therefore a compilation error.

+8
source

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


All Articles