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