Henry Asare
Henry Asare

Reputation: 23

Extra Argument In Call

I am trying to initialize a class and I am getting this error and can't for the life of me figure it out.

class Document {
    var title:String
    var body = ""
    var length: Int {
        get {
            return body.characters.count
        }
    }

    init(title:String) {
        self.title = title
    }
}

let document1 = Document(title: "The Day", body: "It was a day to remember.") //error here on body

Upvotes: 0

Views: 869

Answers (1)

LinusG.
LinusG.

Reputation: 28982

The thing is, you‘re telling the Document class to take a title only when creating a new Document instance.
If you want to also pass a body when initializing, change your initializer to:

init(title: String, body: String) {
    self.title = title
    self.body = body
}

Extra credit:

Say, you don’t always want to pass a body when initializing a new Document, add a default value to body:

init(title: String, body: String = "") {
    self.title = title
    self.body = body
}

Then you can just do:

let doc = Document(title: "Test Doc")

Upvotes: 2

Related Questions