在swift中没有隐试转换,swift会根据你写的值推测类型,数组的话它根据第一个来判断
--for each 循环
for后面写你定义的变量
in后面写你要遍历的对象
let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 3. for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 8. } }
-----------if循环
变量可以在if里面定义 let name
在String中写入一个值:写一个值在括号里,和写一个反下斜线(\)在括号前
optionalNanme 可选的值,可能会丢失
var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" }
------- switch循环
这里可看到switch中的case可一有多个条件,并不是简单的对等
let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let vegetableComment = "Everything tastes good in soup." }
------for循环
啥时候用for循环,在一中范围内的循环,开始,有结束
var secondForLoop = 0 for var i = 0; i < 3; ++i { secondForLoop += 1 } secondForLoop var firstForLoop = 0 for i in 0..3 { firstForLoop += i } firstForLoop
--------内嵌套循环
找三个数组中的最大值
(kind, numbers) 代表了 kind代表""里的东西
number代表了那个数组
用(kind, numbers)来循环数组
用number来循环数组里的数
let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } largest
--------------------------while循环--do--while--
下面两个循环运行结果是一样的,但do-while是无论如何都会执行一次,而while是在满足条件才会执行;
var n = 2 while n < 100 { n = n * 2 } n var m = 2 do { m = m * 2 } while m < 100 m
原文:http://www.cnblogs.com/kangniuniu/p/4882675.html