swift - 有没有更简洁的方法来编写这个 if/else 脚本?

标签 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")
}

最佳答案

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

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

然后您甚至可以将 if {} else {} 结构替换为 switch 语句。

关于swift - 有没有更简洁的方法来编写这个 if/else 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37708584/

相关文章:

swift - 如何在 Swift 中子类化自定义 UIViewController?

html - 如何在ios标签中显示html格式的文本

ios - 使用 Swift 5 的 Vapor 安装问题(第一次使用 Vapor)

swift - 如何查看精确调整大小的图像是否放入 Vision 框架?

iOS:来自 iOS14 EXC_BAD_ACCESS 线程队列的随机错误消息:NSManagedObjectContext NSInternalAdditionsforgetObjectpropagateToObjectStore

swift - 围绕网络创建响应式(Reactive)包装器

ios - 将 prepareForSegue 用于 TableView Controller

ios - ScrollView 不会快速滚动

ios - 什么时候使用?、!、无或惰性?

swift - 如何在 iOS 10/Swift 3 中请求远程权限