Quicksillver
Quicksillver

Reputation: 307

Initializer for a simple class in Swift erroring out

I'm trying to create a class to learn Unit Testing. However, I'm facing some issues which I am struggling with.

My Class:

import Foundation

class Monster{

var name: String{
    didSet(newName){
        self.name = validateName(newName: self.name)
    }
}

var level: Int{
    didSet(level){
        if self.level < 0 {
            self.level = 0
        }else if self.level > 100 {
            self.level = 100
        }
    }
}

var hitpoints: Int{
    didSet(newHP){
        print(self.hitpoints)
        if self.hitpoints < 0 {
            self.hitpoints = 0
        }else if self.hitpoints > self.level * 20{
            self.hitpoints = self.level * 20
        }
    }
}

init(name: String, argLevel: Int, argHP: Int) {
    self.name = name;
    self.level = argLevel
//      self.hitpoints = validateHP(newHP: argHP, curLevel: argLevel)
    let newHP = validateHP(newHP: argHP, curLevel: argLevel)
    self.hitpoints = newHP
    self.name = validateName(newName: name)
}

private func validateName(newName: String) -> String{
    return newName.replacingOccurrences(of: ",", with: "")
}

private func validateHP(newHP: Int, curLevel: Int) -> Int{
    if newHP < 0 {
        return 0
    }else if newHP > 20 * curLevel {
        return 20 * curLevel
    }else{
        return newHP
    }
}

}

I'm not able to use this class as I'm getting an error for using validateHP() function in the initializer.

The error: Desktop/UnitTest/UnitTesting/Monster.swift:44:15: Use of 'self' in method call 'validateHP' before all stored properties are initialized

I do not understand this message as I'm not using any stored properties in the function definition or as one of the arguments. Infact, I changed up the entire argument structure so that this would not happen.

If anyone can educate me on what I'm missing here, that would be really helpful.

Upvotes: 2

Views: 54

Answers (1)

vacawama
vacawama

Reputation: 154721

You can't call an instance method before your instance is initialized. Try making your validateHP and validateName static functions:

init(name: String, argLevel: Int, argHP: Int) {
    self.name = name;
    self.level = argLevel
    //      self.hitpoints = validateHP(newHP: argHP, curLevel: argLevel)
    let newHP = Monster.validateHP(newHP: argHP, curLevel: argLevel)
    self.hitpoints = newHP
    self.name = Monster.validateName(newName: name)
}

private static func validateName(newName: String) -> String {
    return newName.replacingOccurrences(of: ",", with: "")
}

private static func validateHP(newHP: Int, curLevel: Int) -> Int {
    if newHP < 0 {
        return 0
    } else if newHP > 20 * curLevel {
        return 20 * curLevel
    } else {
        return newHP
    }
}

Note: Swift likes spaces around tokens. I suggest using a space before and after { and } to separate them from other elements.

Upvotes: 2

Related Questions