switch-case
用於比較static var
s未按預期工作。但是,指定類型或直接比較的作品。請看下面:Swift static var in switch case
class AnimalHelper {
func loadAnimal(_ animal: Animal) {
// Doesn't compile
switch animal {
case .squirrel, .deer: loadGrass()
case .dolphin: return // not implemented
default: loadMeat()
}
// Direct comparison works
if animal == .squirrel || animal == .deer {
loadGrass()
} else if animal == .dolphin {
return // not implemented
} else {
loadMeat()
}
// Specifying the type explicitly also works
switch animal {
case Animal.squirrel, Animal.deer: loadGrass()
case Animal.dolphin: return // not implemented
default: loadMeat()
}
}
func loadGrass() {}
func loadMeat() {}
}
class Animal {
let id = 6 // Will be generated
let hasFourLegs = true
let numberOfEyes = 2
// ... //
static var squirrel: Animal { return .init() }
static var dolphin: Animal { return .init() }
static var puma: Animal { return .init() }
static var deer: Animal { return .init() }
}
extension Animal: Equatable {
public static func ==(lhs: Animal, rhs: Animal) -> Bool {
return lhs.id == rhs.id
}
}
我相信一些關於上面是不太正確的,因爲它的我得到以下編譯錯誤:
Enum case 'squirrel' not found in type 'Animal'
Enum case 'deer' not found in type 'Animal'
Enum case 'dolphin' not found in type 'Animal'
請讓我知道如何檢查在switch-case
中的相同性與if
條件中的相同。
用確切的錯誤信息更新您的問題並指出導致錯誤的行。 – rmaddy