Swift:控制流

2016-04-21  本文已影响33人  厨子
Control Flow

github:Swift基础实例
github:SwiftBasicTableView

简介

条件语句用 ifswitch ;循环语句使用 for-in,for,while,repeat-while。其中,条件和循环变量两侧不用写圆括号(),但是大括号{}不能省:

let individualScores = [22,33,55,66]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore+=3
    }
    else {
        teamScore+=1
    }
}
print(teamScore)
条件语句
  1. if
    if 声明中,条件必须是一个 bool 表达式。比如上面代码中 if score > 50 { ... } 是对的,如果变为if score { ... } 则会报错 Type 'Int' does not conform to protocol 'BooleanType'

  2. iflet 可以搭配一个可选值进行使用,之所以称为可选值,是因为这个值要么包含一个值,要么是一个空 nil。在一个值的类型后加上一个问号 ? 表示此值可选:

var optionalString : String? = "Hello kitty"
print(optionalString == nil)  
var optionalName: String? = "Swift"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}
else {
    print(optionalName)
}
  1. 缺省值表达式
    可以用操作符 ?? 来提供一个默认值,当值为空的时候,使用提供的默认值:
let nickName: String? = nil
let fullName: String = "Swift"
let informalGreeting = "Hi \(nickName ?? fullName)"
循环语句
  1. switch
    switch 支持任何类型的数据以及多样的比较操作符
let vegetable = "red pepper"
switch vegetable {
    case "celery":
        print("Add some raisins")
    case "cucumber", "watercress":
        print("That would make a good tea sandwich")
    case let x where x.hasSuffix("pepper"):
        print("Is it a spicy \(x)?")
    
    default:
        print("Everything tastes good in soup.")
  1. for-in
    for-inOC 语言中的格式 for (<#type *object#> in <#collection#>),咋 swift 语言中,type 是选填的:
var shoppingList = ["fish","water"]
for name in shoppingList {
   print(name)
}
  1. for-in 迭代字典
    for-in 中,可以用一对名字(key,value)来表示字典中的键值对 key-value ,进行迭代字典中的值,字典是无序的,所以键值对的迭代顺序也是随机的:
var largest = 0
var largestKind = ""
let interestingNumbers = ["Prime":[2,3,5,7],"Square":[1,4,9,16,25]]
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largestKind = kind
            largest     = number
        }
    }
}
print(largest)
print(largestKind)
  1. for-in 和范围符 ..<
    valueOne..<valueTwo 的取值范围是包含valueOne,不包括valueTwo。下面的两段代码都是运算 5!
   var factorial = 5
   for i in 1..<5 {
       factorial = (5-i)*factorial
   }
   print(factorial)

   var factorialTwo = 5
   for var i = 1; i < 5; i++ {
       factorialTwo = (5-i)*factorialTwo
   }
   print(factorialTwo)
  1. while
    while 来重复执行一块代码,直到条件发生改变。条件可以放在最后,这样 while 会至少执行一次。
   var whileNumber = 2
   while whileNumber < 3 {
       whileNumber += 1
   }
   print(whileNumber)

   var whileNumber2 = 2
   repeat {
       whileNumber2 += 1
   } while whileNumber2 < 2
   print(whileNumber2)
上一篇 下一篇

猜你喜欢

热点阅读