[英]Swift 3: Class and Struct Optionals
我已經很長時間從編碼Obj-c過渡到Swift 3了。 所以我想我理解可選的想法,但是我對這個問題感到困惑。 假設我有一個名為Monster的課程。 我也有一個叫做Town的結構。
struct Town {
var population: Int = 0
var name: String?
var hasSherrif: Bool?
var hasTheater: Bool?
var hasTownhall: Bool?
var hasSchool: Bool?
var hasGeneralStore: Bool?
var numOfHomes: Int = 0
}
還有怪物
class Monster {
var town: Town?
var name: String?
func moveToTown(_ thisTown: Town) {
town = thisTown
if let strName = name, let strTownName = town?.name {
print("\(strName) moved to \(strTownName)")
} else if let strName = name {
print("\(strName) move to a town with no name")
} else {
print("The monster moved to a town. Might help if you give stuff names, just saying.")
}
}
}
在moveToTown(_ thisTown:Town)中,如何檢查Monster是否沒有名字,而Town是否呢? 我想更改此行:
} else if let strName = name {
像
} else if let strName = name && town?.name == nil {
然后添加另一個條件
} else if strName == nil && let strTownName = town?.name {
}
謝謝,如果有什么需要清理的地方,隨時可以批評。
您不能使用town?.name
因為town
不是可選的。
無需town = thisTown
行。 只需將參數命名為town
。
我會這樣寫:
func moveToTown(_ town: Town) {
if let name = name {
if let townName = town.name {
print("\(name) moved to \(townName)")
} else {
print("\(name) move to a town with no name")
}
} else {
print("The monster moved to a town. Might help if you give stuff names, just saying.")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.