// Playground - noun: a place where people can play
import Cocoa
//控制流
//Swift的条件语句包括if和switch,循环语句包含for-in、for、while和do-while,循环/判断条件不需要括号,但循环/判断体(body)必需括号:
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
}else{
teamScore += 1
}
}
//可空类型
//结合if和let,可以方便的处理可空变量(nullable variable)。对于空值,需要在类型声明后添加?显示标明该类型可空。
var optionalString: String? = "Hello"
optionalString = nil
var optionalName: String? = "John Applesed"
var gretting = "Hello!"
if let name = optionalName{
gretting = "Hello, \(name)"
}
//灵活的switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add som 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-in 除了遍历数组也可以用来遍历字典
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
}
}
}
//while循环和do-while循环
var n = 2
while n < 100 {
n = n * 2
}
n
var m = 2
do{
m = m * 2
}while m < 100
m
//Swift支持传统的for循环,此外也可以通过结合..(生成一个区间)和for-in实现同样的逻辑
var firstForLoop = 0
for i in 0..3{
firstForLoop += i
}
firstForLoop
var secondForLoop = 0
for var i = 0; i < 3; ++i{
secondForLoop += 1
}
secondForLoop
//注意:Swift除了..还有... 其中..生成前闭后开的区间,而...生成前闭后闭的区间。
var third = 0
for i in 0...3 {
third += i
}
third