Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Extra Argument in call

Tags:

swift

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.

In ViewController class:

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

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

In detailViewController Class

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

This is pretty simple yet I'm baffled.

like image 254
Marin Avatar asked Jul 17 '14 04:07

Marin


2 Answers

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)
    }
}

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)
    }
}

Voila, no more error.

like image 147
Jesse Rosalia Avatar answered Oct 17 '22 05:10

Jesse Rosalia


SwiftUI:

This error message "extra argument in call" is also shown, when all your code is correct, but the maximum number of views in a container is exceeded (in SwiftUI). The max = 10, so if you have some different TextViews, images and some Spacers() between them, you quickly can exceed this number.

I had this problem and solved it by "grouping" some of the views to a sub container "Group":

        VStack {
            
            Text("Congratulations")
                .font(.largeTitle)
                .fontWeight(.bold)
            
            Spacer()
            
            // This grouping solved the problem
            Group {
                Text("You mastered a maze with 6 rooms!")
                Text("You found all the 3 hidden items")
            }
            
            Spacer()

            // other views ...
             
        }
like image 40
LukeSideWalker Avatar answered Oct 17 '22 06:10

LukeSideWalker