对于小于或大于Swiftswitch语句感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍switch语句大于等于,并为您提供关于4.7Swift中swift中的switch语句、4.8Swift
对于小于或大于Swift switch语句感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍switch语句大于等于,并为您提供关于4.7 Swift中swift中的switch 语句、4.8 Swift中switch语句区间和元组模式匹配、4.9 Swift中switch语句值绑定模式、if 与 switch语句的有用信息。
本文目录一览:- 小于或大于Swift switch语句(switch语句大于等于)
- 4.7 Swift中swift中的switch 语句
- 4.8 Swift中switch语句区间和元组模式匹配
- 4.9 Swift中switch语句值绑定模式
- if 与 switch语句
小于或大于Swift switch语句(switch语句大于等于)
我熟悉switch
Swift中的语句,但想知道如何用来替换这段代码switch
:
if someVar < 0 { // do something} else if someVar == 0 { // do something else} else if someVar > 0 { // etc}
答案1
小编典典这是一种方法。假设someVar
是Int
或其他Comparable
,则可以选择将操作数分配给新变量。这样,您就可以使用where
关键字来对其进行范围划分:
var someVar = 3switch someVar {case let x where x < 0: print("x is \(x)")case let x where x == 0: print("x is \(x)")case let x where x > 0: print("x is \(x)")default: print("this is impossible")}
可以简化一下:
switch someVar {case _ where someVar < 0: print("someVar is \(someVar)")case 0: print("someVar is 0")case _ where someVar > 0: print("someVar is \(someVar)")default: print("this is impossible")}
您还可以where
完全避免关键字与范围匹配:
switch someVar {case Int.min..<0: print("someVar is \(someVar)")case 0: print("someVar is 0")default: print("someVar is \(someVar)")}
4.7 Swift中swift中的switch 语句
/**
switch 语句
*/
let str = "aAbBacdef"
let str2 = "aAbBadef"
let str3 = "aAbBadeff"
// var array = [];
for c in ["A","a",str3]
{
switch c {
// case "a":
case "a","A":
print("ldd")
// 必须有
default:
print("dd")
}
}
/**
case "a":
case "A":
print("ldd")
在 C语言中, 这样写 无论遇到 a A 都会执行 print("ldd");
在 swift中就不允许这样子了,但是可以这样子写
case "a","A": 中间用逗号隔开
*/
// switch value {
// case pattern:
// code
// default:
// }
/**
c 语言中
case 下面有个 break;
如果忘了写break, 会顺序执行下面的语句,直到执行break;
但是swift语言就是看到这一点就,不要break了。比较case里面的条件后,
执行完毕后面的语句就自动退出 该switch语句了。
如果想要继续执行 用fallthrough
*/
4.8 Swift中switch语句区间和元组模式匹配
// switch 的广义匹配
let x = 1000
// 也就是说并没有像C语言那样 要求 switch 后面的是整数常量
switch x {
// case后面可以跟区间啦
case 1...9:
print("个位数")
case 10...99:
print("十位数")
case 100...999:
print("百位数")
case 1000...9999:
print("千位数")
default:
print("不符合")
}
let point = (10,10)
// switch 后面可以跟一个元组类型
switch point {
case (0,0):
print("坐标原点")
case (1...10,1...10):
print("x和y坐标范围是位于1-10之间的")
case(_,27)">点在 x 轴上")
default:
print("其他")
}
4.9 Swift中switch语句值绑定模式
// switch语句值绑定模式
let point = (100,10)
switch point {
// 遇到有匹配的就不会在执行下一个了 这样子也可以啊case let (x,y)
case (let x,let y):
print("\(x): \(y)")
// 还可以加个判断,同时满足匹配 同时 x == -10
case (let x,10) where x == -10:
// 匹配y坐标为10 的
print(x);
default:
print("其他")
}
if 与 switch语句
总结
以上是小编为你收集整理的if 与 switch语句全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
今天关于小于或大于Swift switch语句和switch语句大于等于的分享就到这里,希望大家有所收获,若想了解更多关于4.7 Swift中swift中的switch 语句、4.8 Swift中switch语句区间和元组模式匹配、4.9 Swift中switch语句值绑定模式、if 与 switch语句等相关知识,可以在本站进行查询。
本文标签: