对不起,我是斯威夫特的小伙子,还在学习。
我从Xcode获得以下错误消息以获取以下快速代码:“无法将类型'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..")
}
}
}
这是Town结构:
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
}
}
为什么我收到此错误消息?
答案 0 :(得分:2)
错误很明显
无法将'Town?.Type'(又名'Optional.Type')类型的值转换为预期参数类型'Town?
表示您传递类型而不是类型的实例。
而不是Town?
传递town
:
vampirePopulation.append(Vampire(town: town, monsterName: name))