【发布时间】:2014-12-31 19:57:30
【问题描述】:
假设我有一个协议:
public protocol Printable {
typealias T
func Print(val:T)
}
这是实现
class Printer<T> : Printable {
func Print(val: T) {
println(val)
}
}
我的期望是我必须能够使用Printable 变量来打印这样的值:
let p:Printable = Printer<Int>()
p.Print(67)
编译器抱怨这个错误:
"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)
编辑 2:我想要的真实世界示例。请注意,这不会编译,但会呈现我想要实现的目标。
protocol Printable
{
func Print()
}
protocol CollectionType<T where T:Printable> : SequenceType
{
.....
/// here goes implementation
.....
}
public class Collection<T where T:Printable> : CollectionType<T>
{
......
}
let col:CollectionType<Int> = SomeFunctiionThatReturnsIntCollection()
for item in col {
item.Print()
}
【问题讨论】:
-
这是 2014 年 Apple 开发者论坛上的一个相关主题,Apple 的 Swift 开发者在一定程度上解决了这个问题:devforums.apple.com/thread/230611(注意:需要 Apple 开发者帐户才能查看此页面。)