是否有更简洁的方法来编写这个if / else脚本?

时间:2016-06-08 16:56:40

标签: swift

学习Swift,好奇是否有更简洁的方法来编写这段代码?

var apple = 1
var orange = 1
var kiwi = 1

if (orange > apple) && (orange > kiwi) {
    print("The orange is the best")
} else if (apple > orange) && (apple > kiwi) {
    print("The apple is the best")
} else if (kiwi > apple) && (kiwi > orange) {
    print("The kiwi is the best")
} else {
    print("None of them are the best")
}

1 个答案:

答案 0 :(得分:2)

我不是一个快速的专家,但是从您的代码示例中,您似乎可以使用max函数:

func max<T : Comparable>(x: T, y: T, rest: T...) -> T

然后,您甚至可以使用if {} else {}语句替换switch结构。