Swift学习之十二:控制流

/* 
   控制流
   for for-in while do-while 
*/

let count = 5
for var i = 0; i < count; i++ {
  print("\(i)")
}

for i in 0..count {
  print("\(i)")
} 

let base = 4
let power = 10
var answer = 1
// 使用_来忽略某个值
for _ in 1...power {
   answer *= base
}

// 访问数组
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
  println("Hello, \(name)")
}

// 访问字典
let numberOfLegs = ["spider" : 8, "ant" : 6, "cat" :4]
for (key, value) in numberOfLegs {
   println("\(key)s have \(value) legs")
}

// 循环遍历字符串
for c in "Hello" {
   print(c)
}

var index: Int 
for index = 0; index < 4; ++index {
   println("Index is \(index)")
}


// while循环
let times = 10
var count = 0
while count < times {
  print("\(count++)")
}

// do-while循环
let times = 10
var count = 0
do {
  count++
  println("\(count)")
} while count < times



// switch 语句在swift中与C和OC中是不同的,在Swift中匹配到一个Case后,不需要添加break,
// 也会在执行完匹配的那一项后自动Break。
let c = "a"
switch c {
case "a" : print("a")
case "b" : print("b")
case "c" : print("c")
default: print("default")
}
// print a

// 范围匹配
let count = 1_000_000
var msg: String
switch count {
case 0: msg = "no"
case 1...3: msg = "a few"
case 10...99: msg = "lower than one hundred"
case 100...999: msg = "lower than one thousand"
case 1000...9999: msg = ”lower than then thousand“
case 10000...99999: msg = "lower than one million"
default: msg = "no value"
}

上一篇:以太网发展:性能是基础 功能及开放是进阶


下一篇:轻松学——操作系统之存储