相关疑难解决方法(0)

如何将通用协议用作变量类型

假设我有一个协议:

public protocol Printable {
    typealias T
    func Print(val:T)
}
Run Code Online (Sandbox Code Playgroud)

这是实施

class Printer<T> : Printable {

    func Print(val: T) {
        println(val)
    }
}
Run Code Online (Sandbox Code Playgroud)

我的期望是我必须能够使用Printable变量来打印这样的值:

let p:Printable = Printer<Int>()
p.Print(67)
Run Code Online (Sandbox Code Playgroud)

编译器抱怨此错误:

"protocol'Printable'只能用作通用约束,因为它具有Self或相关的类型要求"

难道我做错了什么 ?有任何解决这个问题的方法吗 ?

**EDIT :** Adding similar code that works in C#

public interface IPrintable<T> 
{
    void Print(T val);
}

public class Printer<T> : IPrintable<T>
{
   public void Print(T val)
   {
      Console.WriteLine(val);
   }
}


//.... inside Main
.....
IPrintable<int> p = new Printer<int>();
p.Print(67)
Run Code Online (Sandbox Code Playgroud)

编辑2:我想要的真实世界的例子.请注意,这不会编译,但会呈现我想要实现的目标.

protocol Printable …
Run Code Online (Sandbox Code Playgroud)

generics xcode ios swift

81
推荐指数
2
解决办法
3万
查看次数

标签 统计

generics ×1

ios ×1

swift ×1

xcode ×1