Gold Challenge

Follows my solution to the challenge:

Monster.swift:

required init?(town: Town?, monsterName: String?) { if monsterName == nil { print("Name is empty. Initialization failed!") return nil } self.town = town name = monsterName }

Zombie.swift:

[code]init?(limp: Bool, fallingApart: Bool, town: Town?, monsterName: String?) {
walksWithLimp = limp
isFallingApart = fallingApart
super.init(town: town, monsterName: monsterName)
}

convenience required init?(town: Town?, monsterName: String?) {
self.init(limp: false, fallingApart: false, town: town, monsterName: monsterName)
}

[/code]

Monster:

required init?(town: Town?, monsterName: String) {
        if monsterName == "" {
            return nil
        }
        self.town = town
        name = monsterName
    }

Zombie:

    init?(limp: Bool, fallingApart: Bool, town: Town?, monsterName: String) {
        walksWithLimp = limp
        isFallingApart = fallingApart
        super.init(town: town, monsterName: monsterName)
    }
    
    convenience init?(limp: Bool, fallingApart: Bool) {
        self.init(limp: limp, fallingApart: fallingApart, town: nil, monsterName: "Fred")
        if walksWithLimp {
            print("This zombie has a bad knee.")
        }
    }
    
    convenience required init?(town: Town?, monsterName: String) {
        self.init(limp: false, fallingApart: false, town: town, monsterName: monsterName)
    }

[quote=“duducaribeiro”]Follows my solution to the challenge:

Monster.swift:

required init?(town: Town?, monsterName: String?) { if monsterName == nil { print("Name is empty. Initialization failed!") return nil } self.town = town name = monsterName }[/quote]
The challenge is to prevent a Monster from having an empty string for a name. This code uses a String? to ensure that the monsterName parameter exists, but does not prevent the String from being empty.

I found it easier to instead leave monsterName as a non-optional type (exactly like astericky’s code, except I happened to use monsterName.isEmpty in the conditional), and then rely on the compiler to enforce providing an actual String value for the parameter when creating a Zombie? in Main.swift.

Please check my solution: