Alex Owen-Meehan
Alex Owen-Meehan

Reputation: 13

Swift "Extra Argument in Call" error when using .append to an array of classes

I've just recently started learning Swift, and as part of one of my programs, I've been trying to maintain an array of class instances and use .append to add new instances to the array of classes.

However, when attempting to append a new class instance to the array, the "Extra Argument in Call" error appears. I have been sure to specify data types for all variables to ensure that there is not a compiler error with conflicting data types, but this has still not fixed the problem.

Here is the code:

import UIKit

var personMgr: personManager = personManager()

class person{

    var name:String = "Default"
    var description:String = "Default"
    var presentIdeasDict:[Int: String] = [
        0: "nil"
    ]
    var presentLinkDict:[Int: String] = [       //Use same key for name of present idea and link for the present
    0: "nil"
    ]

}

class personManager{

    var people = [person]()

    func addPerson(name: String, description: String){
        people.append(person(name: name, description: description, presentIdeasDict: [0: "nil"], presentLinkDict: [0: "nil"]))
    }

}

The error says "Extra argument 'name' in call in the line:

people.append(person(name: name, description: description, presentIdeasDict: [0: "nil"], presentLinkDict: [0: "nil"]))

Upvotes: 1

Views: 1974

Answers (1)

Eric Aya
Eric Aya

Reputation: 70111

You need to make an initializer for your "person" class.

Note that you can set default values for the initializer parameters too. This way you won't have to use the defaults in several places (you can even omit the default parameters in other initializers).

Also note that by convention a class name should be capitalized.

Example:

class Person {

    var name:String
    var description:String
    var presentIdeasDict:[Int: String]
    var presentLinkDict:[Int: String]

    init(name: String = "Default", description: String = "Default", presentIdeasDict: [Int: String] = [0: "nil"], presentLinkDict: [Int: String] = [0: "nil"]) {
        self.name = name
        self.description = description
        self.presentIdeasDict = presentIdeasDict
        self.presentLinkDict = presentLinkDict
    }

}

class PersonManager {

    var people = [Person]()

    func addPerson(name: String, description: String) {
        people.append(Person(name: name, description: description))
    }

}

Upvotes: 1

Related Questions