我正在尝试创建一个Switch语句( Swift),当case大于给定数字时返回一个String.我知道这可以通过“if”或“else if”语句完成,但我希望用Switch语句来完成这个.可以这样做还是Switch语句无法使用
var score = 101 var letterGrade = "" switch score{ case >100: letterGrade = "A+ With Extra Credit" case 90...100: letterGrade = "A" case 80...89: letterGrade = "B" case 70...79: letterGrade = "C" case 60...69: letterGrade = "D" default: letterGrade = "Incomplete" }是一个简单的解决方案,将它绑定到这样的常量:
var score = 101 var letterGrade = "" switch score{ case let x where x > 100: letterGrade = "A+ With Extra Credit" case 90...100: letterGrade = "A" case 80...89: letterGrade = "B" case 70...79: letterGrade = "C" case 60...69: letterGrade = "D" default: letterGrade = "Incomplete" }
这完全符合您的需要