Swift Question

I’m new to Swift and I’m reading a book that gave me the following challenge


Make a new type called Mayor. It should be a struct. The Town type should have a property called mayor that holds an instance of the Mayor type. Have your town inform the mayor every time the property for population changes. If the town’s population decreases, have the instance of the Mayor log this statement to the console: “I’m deeply saddened to hear about this latest tragedy. I promise that my office is looking into the nature of this rash of violence.” If the population increases, then the mayor should do nothing. (Hint: You should define a new instance method on the Mayor type to complete this challenge.)


Here’s what I have:


import Foundation
struct Mayor {

       mutating func informTheMayor(from population: Int, to newPopulation: Int) -> String {
        if newPopulation < population  {
            return "I'm deeply saddened to hear about this latest tradgedy. I promise that my office is looking into the nature of this rash of violence.")
        } else {
           return " "



I feel like there's a better way to write this. I wanted to exit the method if the condition was not met (instead of returning an empty string), is there a way to do that?



Here's what I have for town.swift:


import Foundation
struct Town {

    var mayor = Mayor()

    static let region = "South"
    var population = 5_422 {
        willSet(newPopulation) {
                if newPopulation < population {
                print("The population has changed to (newPopulation) from (population).")
                mayor.informTheMayor(from: population, to: newPopulation)          


Could someone help me understand why I get the warning for town.swift:


Result of call to 'informTheMayor(from:to:)' is unused


I thought that calling the method would print the message "I'm deeply saddened..."  . How is it unused? I tried many different things including wrapping the method in print() and it still won't work. There must be a concept I'm not understanding here? Why won't the message print as expected?

Powered by WPeMatico

You may also like...

Comments are closed.