【发布时间】:2021-04-02 11:49:00
【问题描述】:
下面的代码只是解释程序的示例代码,因为原始代码过于复杂和冗长。我创建了Game 对象的一个实例。它可以是三个Cartypes 之一。
MainClass 中的 foo() 函数被调用超过 100 次。
每次调用 foo() 检查对象的类型似乎违反直觉,因为我一开始就知道 obj 的类型。出于性能和简单性的原因,我想避免使用 if 语句。有什么更好的方法来实现这一点?
class Car{
init(type: CarType, color: String){
self.type = type
self.color = color
}
}
enum Cartypes{
case sedan
case pickup
case coupe
}
class MainClass{
// this is just an example, it could be any other cartype as well
let obj = Car(type: .sedan, color: "red")
func foo(){
if obj.type == .sedan{
doSedanStuff()
} else if obj.type == .pickup{
doPickupStuff()
} else if obj.type == .coupe{
doCoupeStuff()
}
}
【问题讨论】:
标签: swift performance if-statement types