Chapter 15, Silver Challenge Solution

I modified main.swift and added a Vampire.swift class to my project.

//
//  main.swift
//  MonsterTown
//

import Foundation

var myTown = Town()
myTown.changePopulation(by: 500)

let fredTheZombie = Zombie()
fredTheZombie.town = myTown
fredTheZombie.terrorizeTown()
fredTheZombie.town?.printDescription()

let vicTheVampire = Vampire()
vicTheVampire.town = myTown
vicTheVampire.terrorizeTown()
vicTheVampire.town?.printDescription()
print("Vic has \(vicTheVampire.thralls.count) thrall.")
vicTheVampire.terrorizeTown()
vicTheVampire.town?.printDescription()
print("Vic has \(vicTheVampire.thralls.count) thralls.")
vicTheVampire.terrorizeTown()
vicTheVampire.town?.printDescription()
print("Vic has \(vicTheVampire.thralls.count) thralls.")
//
//  Vampire.swift
//  MonsterTown
//

import Foundation

class Vampire: Monster {
    var thralls = [Vampire]()
    
    override func terrorizeTown() {
        // Try to capture one of the townspeople.
        if town?.population ?? 0 > 0 {
            town?.changePopulation(by: -1)
            thralls.append(Vampire())
        }
        super.terrorizeTown()
    }
}

Iā€™m curious whether there is a more concise way to write the population check.

This version of the method is more verbose, but the if-statement is easier to comprehend. :slight_smile:

    override func terrorizeTown() {
        // Try to capture one of the townspeople.
        let population = town?.population ?? 0
        if population > 0 {
            town?.changePopulation(by: -1)
            thralls.append(Vampire())
        }
        super.terrorizeTown()
    }
1 Like