美文网首页
Swift 中的switch 语句

Swift 中的switch 语句

作者: tech_go | 来源:发表于2023-04-09 11:27 被阅读0次

在 Swift 中,switch 语句的例子(不需要break):

let fruit = "apple"
switch fruit {
case "apple":
    print("This is an apple.")
case "banana":
    print("This is a banana.")
case "orange":
    print("This is an orange.")
default:
    print("Unknown fruit.")
}

还可以使用多个条件,使用逗号分隔开,例如:

let score = 85
switch score {
case 0..<60:
    print("Failed")
case 60..<70:
    print("Pass")
case 70..<80:
    print("Good")
case 80..<90:
    print("Great")
case 90...100:
    print("Excellent")
default:
    break
    // 空的 default 语句
}

必须包含default能处理所有情况 (case,default后面至少要有一条语句,空的需要加上break)。

相关文章

网友评论

      本文标题:Swift 中的switch 语句

      本文链接:https://www.haomeiwen.com/subject/iudbddtx.html