如何在下面的函数中重构以下嵌套的swift if语句?

时间:2018-06-18 07:42:40

标签: swift refactoring

以下函数完成了这项工作,但我觉得我可以通过重构下面的if语句数来更好地清理我的代码。

我想将preferredGender的值设置为femalemaleboth,具体取决于是否设置了preferMenpreferWomentruefalse

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

1 个答案:

答案 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)
  

输出男士