Search code examples
swift2nsdatanscoding

Extra argument in call in self.init Swift 2.2


I've been searching for this error and reading various stackoverflow, Apple documentation and blog answers but I'm still having issues. I have a class conforming to NSData and NSCoding for which of 3 of 6 properties will be stored. When calling self.init in the required convenience init, I get an error "Extra argument 'groomedStatus' in call," even though the self.init signature matches init exactly (I copied and pasted). This is the relevant code:

class Trail: NSObject, NSCoding {
var name: String
var difficulty: Difficulty
var haveSkied: Bool
var season: Season = .winter
var open: String?
var groomedStatus: String?

init(name: String, difficulty: Difficulty, haveSkied: Bool, season: Season, open: String?, groomedStatus: String?) {
    self.name = name
    self.difficulty = difficulty
    self.haveSkied = haveSkied
    self.season = season
    self.open = open
    self.groomedStatus = groomedStatus
}

required convenience init(coder aDecoder: NSCoder) {

    let haveSkied = aDecoder.decodeObjectForKey("haveSkied") as! Bool
    let open = aDecoder.decodeObjectForKey("open") as? String
    let groomedStatus = aDecoder.decodeObjectForKey("groomedStatus") as? String


    self.init(name: String, difficulty: Difficulty, haveSkied: Bool, season: Season, open: String?, groomedStatus: String?) {
        self.name = name
        self.difficulty = difficulty
        self.haveSkied = haveSkied
        self.season = season
        self.open = open
        self.groomedStatus = groomedStatus
    }

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeBool(haveSkied, forKey: "haveSkied")
    aCoder.encodeObject(open, forKey: "open")
    aCoder.encodeObject(groomedStatus, forKey: "groomedStatus")
}

}


Solution

  • The problem results from how you call self.init(). The way you're doing it in your code is essentially an attempt to redefine it, which makes no sense to the compiler. This is how you should be calling self.init() in your convenience initializer.

    self.init(name: "yourActualNameString", difficulty: Difficulty(), haveSkied: true, season: .winter, open: "yourActualOpenString", groomedStatus: "yourActualGroomedStatusString")