Swift - 调用中的额外参数 [英] Swift - Extra Argument in call

查看:26
本文介绍了Swift - 调用中的额外参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从 DetailViewController 类调用在 ViewController 类中声明的函数.

I am trying to call a function declared in ViewController class from DetailViewController class.

尝试调试调用中的额外参数"错误时会弹出.

When trying to debug the 'Extra Argument in call" error pops up.

在 ViewController 类中:

In ViewController class:

func setCity(item : Cities, index : Int)
{

    citiesArray!.removeObjectAtIndex(index)
    citiesArray!.insertObject(item, atIndex: index)
}

详细ViewController类

In detailViewController Class

 // city of type Cities
 ViewController.setCity(city ,5 ) //Error: "Extra argument in call" 

这很简单,但我很困惑.

This is pretty simple yet I'm baffled.

推荐答案

在某些情况下,即使调用看起来正确,如果参数的类型与函数的类型不匹配,也会给出调用中的额外参数"宣言.从您的问题来看,您似乎正在尝试将实例方法作为类方法调用,我发现这是其中一种情况.例如,此代码给出了完全相同的错误:

In some cases, "Extra argument in call" is given even if the call looks right, if the types of the arguments don't match that of the function declaration. From your question, it looks like you're trying to call an instance method as a class method, which I've found to be one of those cases. For example, this code gives the exact same error:

class Foo {

    func name(a:Int, b: Int) -> String {
        return ""
    }
}

class Bar : Foo {    
    init() {
        super.init()
        Foo.name(1, b: 2)
    }
}

您可以在代码中通过将 setCity 的声明更改为 class func setCity(...)(在评论中提到)来解决此问题;这将允许 ViewController.setCity 调用按预期工作,但我猜你希望 setCity 成为一个实例方法,因为它似乎修改了实例状态.您可能想要获取 ViewController 类的实例并使用它来调用 setCity 方法.使用上面的代码示例进行说明,我们可以将 Bar 更改为:

You can solve this in your code by changing your declaration of setCity to be class func setCity(...) (mentioned in the comments); this will allow the ViewController.setCity call to work as expected, but I'm guessing that you want setCity to be an instance method since it appears to modify instance state. You probably want to get an instance to your ViewController class and use that to call the setCity method. Illustrated using the code example above, we can change Bar as such:

class Bar : Foo {    
    init() {
        super.init()
        let foo = Foo()
        foo.name(1, b: 2)
    }
}

瞧,没有更多错误了.

这篇关于Swift - 调用中的额外参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆