我有以下协议,1个var和2个下标:
protocol Universe{
var count: Int{get}
subscript(heroAtIndex index: Int)->SuperPowered {get}
subscript(villainAtIndex index: Int)->SuperPowered {get}
}
尝试在此课程中实施此协议时:
class Marvel: Universe{
var _heroes = [
SuperPowered.heroWithFirstName("Peter", lastName: "Parker", alias: "Spiderman"),
SuperPowered.heroWithFirstName("Scott", lastName: "Summers", alias: "Cyclops"),
SuperPowered.heroWithFirstName("Ororo", lastName: "Monroe", alias: "Storm")]
var _villains = [
SuperPowered.villainWithFirstName("Victor", lastName: "Von Doom", alias: "Dr Doom"),
SuperPowered.villainWithFirstName("Erik", lastName: "Lehnsher", alias: "Magneto"),
SuperPowered.villainWithFirstName("Cain", lastName: "Marko", alias: "Juggernaut")]
// UNiverse protocol
var count : Int{
get{
return _heroes.count + _villains.count
}
}
subscript(heroAtIndex index: Int)->SuperPowered{
return _heroes[index]
}
}
我在las行(下标)上出错。它抱怨说
method 'subscript(heroAtIndex:)' has different argument names from those required by protocol 'Universe' ('subscript(villainAtIndex:)')
subscript(heroAtIndex index: Int)->SuperPowered{
^
我不知道编译器在说什么:名字是相同的,我甚至复制和粘贴。
发生了什么?
答案 0 :(得分:3)
参数可以是命名的也可以是位置的。通过将heroAtIndex index
置于命名参数中;即你必须致电subscript(heroAtIndex:x)
然后您遇到的问题是这两个方法具有完全相同的名称和参数类型。它变得困惑,因为你只是实现了其中一个,它抱怨说,当试图找到另一个的实现时,你得到的参数名称是错误的。
当你实现它们时(正如你的协议所说的那样),不再存在编译时错误,所以问题就像错误消息一样消失了。