灵活的 switch
Swift 中的switch
支持各种各样的比较操作:
let vegetable = "red pepper" switch vegetable { case celery": let vegetableComment = Add some raisins and make ants on a log.cucumber",watercressThat would make a good tea sandwich.case let x where x.hasSuffix (pepper): let vegetableComment = Is it a spicy \(x)?defaultEverything tastes good in soup. }
其它循环本文来自www.itxxz.com
for-in
除了遍历数组也可以用来遍历字典:
let interestingNumbers = [ Prime": [2,128)">3,128)">5,128)">7,128)">11,128)">13],Fibonacci1,128)">8Square4,128)">9,128)">16,128)">25var largest = 0 for (kind,numbers) in interestingNumbers { for number numbers { if number > largest { largest = number } } } largest
while循环和do-while
循环:本文来自www.itxxz.com
var n = 2 while n < 100 { n = n * 2 } n var m = do { m = m * } while m < m
Swift 支持传统的for
循环,此外也可以通过结合..
(生成一个区间)和for-in
实现同样的逻辑。
var firstForLoop = for i in 0..3 { firstForLoop += i } firstForLoop var secondForLoop = for var i = 0; i < 3; ++i { secondForLoop += 1 } secondForLoop