Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra argument in call error mystery

I had some older Swift code that used to compile and work where I was using the .append to build out a data structure dynamically. After upgrading to a few compiler versions newer I am getting the dreaded "Extra Argument ' ' in call" error. I reduced the code down to this:

struct  EHSearch {
    let EHcategory : String = ""
    let EHname : String = ""
}

var  myEHSearch = [EHSearch]()

// Call to dynamically append the results
// Extra argument: 'EHcategory' in call

myEHSearch.append(EHSearch(EHcategory: "Food", EHname: "Joes Crab Shack"))

I can't see anything so far in searching on what has changed to cause this one so seeking guidance here.

like image 824
Kokanee Avatar asked Jan 17 '26 02:01

Kokanee


2 Answers

Because you have let in your struct. Define your structure like this:

struct EHSearch {
    var EHcategory : String = ""
    var EHname : String = ""
}

If you have constants in your struct, you can not provide them initial value while creating new structure instances. The automatically-generated member-wise initializer doesn't accept let members as parameters of the initializer of struct.

like image 172
saurabh Avatar answered Jan 19 '26 19:01

saurabh


It depends on your intentions with the struct's properties. Do you want them to be mutable or not?

If yes, then @sasquatch's answer will do.

If not, then you need to ensure a value is assigned to them only once. As you already do that in the struct declaration (the default values), you can't assign new values to them. But being a struct, they don't need to have default values - moreover, struct automatically receive a memberwise initializer. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

So here is the variant for immutable properties:

struct  EHSearch {
    let EHcategory : String
    let EHname : String
}

var  myEHSearch = [EHSearch]()

// Call to dynamically append the results
// Extra argument: 'EHcategory' in call

myEHSearch.append(EHSearch(EHcategory: "Food", EHname: "Joes Crab Shack"))

The "Extra Argument" error you're seeing is because the compiler already has values for the properties so it doesn't expect any new ones. Here is the "middle" way - one property has a default value whilst the other doesn't - which should make it clearer:

struct  EHSearch {
    let EHcategory : String = ""
    let EHname : String
}

var  myEHSearch = [EHSearch]()

// Call to dynamically append the results
// Extra argument: 'EHcategory' in call

myEHSearch.append(EHSearch(EHname: "Joes Crab Shack"))
like image 37
Paul Ardeleanu Avatar answered Jan 19 '26 18:01

Paul Ardeleanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!