我有以下协议,有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{
^我不知道编译器在说什么:名字是一样的,我甚至复制和粘贴。
到底怎么回事?
发布于 2014-09-26 00:06:12
参数既可以命名,也可以定位。通过放置heroAtIndex index,可以使它成为一个命名的参数;也就是说,您必须调用subscript(heroAtIndex:x)
然后,您会遇到这样的问题:这两个方法的名称和参数类型完全相同。这让人感到困惑,因为你只是在实现其中的一个,这是在抱怨当你试图找出另一个实现时,你的参数名称弄错了。
当您实现这两种方法时(正如您的协议所述,您应该这样做),不再存在编译时错误,因此问题就会消失,就像错误消息一样。
https://stackoverflow.com/questions/26044713
复制相似问题