前端之家收集整理的这篇文章主要介绍了
Swift 条件选择(if Switch),循环结构(三),
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
switch
var i = 0
switch i {
case 0:
print("0")
case 1:
print("1")
default:
print("default")
}
不用加上break,Swift的Switch语句会自动在case结尾处加上break,但是在某些情况下,我们可能会希望Switch能同时执行两条case如下:
var j = 3
switch j {
case 0,3:
print("0,3")
fallthrough
case 1:
print("1")
default:
print("default")
}
支持多种数据类型:浮点,布尔,字符串,支持区间运算符例子如下
var k = 15
switch i {
case 0 ... 10:
break
case 11 ... 20:
break
default:
break
}
let request = (true,"success")
switch request {
case (true,"success"):
print("success")
break
case (false,"Failed"):
print("Failed")
break
default: break
}
支持额外的逻辑判断
let request1 = (0,"success")
switch request1 {
case (0,let state) where state != "success":
state
case (let errorCode,_):
"error code is \(errorCode)"
}
var string:String = "Hello"
if string == "Hello"{
print("YES")
}else{
print("NO")
}
循环for
// for in
for var i in 1...5{
print(i)
}
var ii = 0
while ii < 11
{
print("while")
}
// repeat-while::do-while
var jj = 0
repeat{
}while i < 11
原文链接:https://www.f2er.com/swift/324304.html