首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Swift中实现协议中定义的下标时出错

在Swift中实现协议中定义的下标时出错
EN

Stack Overflow用户
提问于 2014-09-25 17:33:59
回答 1查看 224关注 0票数 0

我有以下协议,有1 var和2下标:

代码语言:javascript
复制
protocol Universe{

    var count: Int{get}

    subscript(heroAtIndex index: Int)->SuperPowered {get}
    subscript(villainAtIndex index: Int)->SuperPowered {get}

}

在尝试在该类中实现此协议时:

代码语言:javascript
复制
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线(下标)上有一个错误。它抱怨说

代码语言:javascript
复制
method 'subscript(heroAtIndex:)' has different argument names from those required by protocol 'Universe' ('subscript(villainAtIndex:)')
        subscript(heroAtIndex index: Int)->SuperPowered{
        ^

我不知道编译器在说什么:名字是一样的,我甚至复制和粘贴。

到底怎么回事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-26 00:06:12

参数既可以命名,也可以定位。通过放置heroAtIndex index,可以使它成为一个命名的参数;也就是说,您必须调用subscript(heroAtIndex:x)

然后,您会遇到这样的问题:这两个方法的名称和参数类型完全相同。这让人感到困惑,因为你只是在实现其中的一个,这是在抱怨当你试图找出另一个实现时,你的参数名称弄错了。

当您实现这两种方法时(正如您的协议所述,您应该这样做),不再存在编译时错误,因此问题就会消失,就像错误消息一样。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26044713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档