對不起,我是Swift的noob,仍然在學習。Swift Xcode錯誤:無法轉換類型的值
我從Xcode收到以下swift代碼的錯誤消息:「無法將類型'Town?.Type'(又名'Optional.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()
}
}
這裏的怪物等級:
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..")
}
}
}
這裏是城市結構:
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
}
}
爲什麼我收到此錯誤訊息?
顯示'Town'類。 – nayem
我添加了Town結構。 – user2959094