user2959094
user2959094

Reputation: 143

Swift Xcode Error: Cannot Convert Value of Type

Sorry, I'm a noob at Swift and still learning.

I'm getting the following error message from Xcode for the following swift code: "Cannot convert value of type 'Town?.Type' (aka 'Optional.Type') to expected argument type 'Town?'"

class Vampire: Monster {

    var vampirePopulation: [Vampire] = []

    override func terrorizeTown() {
        if town?.population > 1 {
        town?.changePopulation(-1)
        } else {
        town?.population = 0
        }
        vampirePopulation.append(Vampire(town: Town?, monsterName: String))
        print("\(vampirePopulation.count) vampires")
        super.terrorizeTown()
    }

}

Here is the Monster Class:

import Foundation

class Monster {
    static let isTerrifying = true
    class var spookyNoise: String {
        return "Grrr"
    }
    var town: Town?
    var name = String ()
    var victimPool: Int {
        get {
            return town?.population ?? 0
        }
        set(newVictimPool) {
            town?.population = newVictimPool
        }
    }
    init(town: Town?, monsterName: String) {
        self.town = town
        name = monsterName
    }
    func terrorizeTown() {
        if town != nil {
            print("\(name) is terrorizing a town!")
        }else {
            print("\(name) hasn't found a town to terrorize yet..")
        }
    }
}

Here is the Town struct:

import Foundation

struct Town {
var mayor: Mayor?
let region: String
var population: Int {
    didSet(oldPopulation) {
if population < oldPopulation
{
    print("The population has changed to \(population) from \
(oldPopulation).")
    mayor?.mayorResponse()
}
}
}



var numberOfStoplights: Int
init(region: String, population: Int, stoplights: Int) {
self.region = region
self.population = population
numberOfStoplights = stoplights
}
init(population: Int, stoplights: Int) {
    self.init(region: "N/A", population: population, stoplights: 
stoplights)
}

enum Size {
    case Small
    case Medium
    case Large
}
var townSize: Size {
    get {
    switch self.population {
    case 0...10000:
        return Size.Small

    case 10001...100000:
        return Size.Medium

    default:
        return Size.Large
    }
}
}
func printTownDescription () {
    print("Population: \(population); number of stoplights: \
(numberOfStoplights); region: \(region)")
}

mutating func changePopulation(_ amount: Int) {
population += amount
}
}

Why am I receiving this error message?

Upvotes: 0

Views: 1446

Answers (1)

vadian
vadian

Reputation: 285059

The error is pretty clear

Cannot convert value of type 'Town?.Type' (aka 'Optional.Type') to expected argument type 'Town?

means that you are passing a type rather than the instance of the type.

Instead of Town? pass town:

vampirePopulation.append(Vampire(town: town, monsterName: name))

Upvotes: 2

Related Questions