use*_*602 7 generics protocols swift
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>
{
}
Run Code Online (Sandbox Code Playgroud)
我认为可以使用符合协议的泛型类型来调用引用相同协议的方法.怎么施展呢?几乎尝试了一切,没有任何工作.也许我理解错了......
对这一个人有什么帮助吗?非常感谢
Bry*_*hen 11
试试这个
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> = {}
Run Code Online (Sandbox Code Playgroud)
正如我在这个答案中所指出的那样,Data<T>没有任何关系Data<Identifiable>.所以你不能使用Data<T>期望Data<Identifiable>的编译错误.