以下函数完成了这项工作,但我觉得我可以通过重构下面的if语句数来更好地清理我的代码。
我想将preferredGender
的值设置为female
,male
或both
,具体取决于是否设置了preferMen
和preferWomen
到true
或false
。
func setUserDiscoveryPreferences(discoveryPrefs: [String : Any]){
preferMen = discoveryPrefs["men"] as? Bool
preferWomen = discoveryPrefs["women"] as? Bool
if preferWomen == true && preferMen == true {
preferredGender = "both"
}
if preferWomen == true && preferMen == false {
preferredGender = "female"
}
if preferWomen == false && preferMen == true{
preferredGender = "male"
}
if preferWomen == false && preferMen == false {
preferredGender = ""
}
}//end func
答案 0 :(得分:2)
您实际上并不需要与true / false进行比较,因此您可以做的第一个改进是:
if preferWomen && preferMen {
preferredGender = "both"
}
if preferWomen && !preferMen {
preferredGender = "female"
}
if !preferWomen && preferMen {
preferredGender = "male"
}
if !preferWomen && !preferMen {
preferredGender = ""
}
对于if语句的长度,尽管使用switch语句通常更好
switch (preferWomen, preferMen) {
case (true, true):
preferredGender = "both"
case (true, false):
preferredGender = "women"
case (false, true):
preferredGender = "men"
case (false, false):
preferredGender = ""
}
游乐场示例
let preferMen = true
let preferWomen = false
var preferredGender = ""
switch (preferWomen, preferMen) {
case (true, true):
preferredGender = "both"
case (true, false):
preferredGender = "women"
case (false, true):
preferredGender = "men"
case (false, false):
preferredGender = ""
}
print(preferredGender)
输出男士