var optionalString: String? = "Hello"
optionalString == nil
var optionalName: String? = "John Appleseed"
//var optionalName: String? = nil
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
} else {
greeting = "Hello, world"
}
可选值为nil条件的结果是false,用let声明的name的作用域
仅在if-else结构中
switch可以使用任何种类的比较数据,而不只是整型数值和相等的比较
1234567891011
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"
}
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;
var largestKind = "";
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largestKind = kind
}
}
}
largest // 25
largestKind // Square
var n = 2
while n < 100 {
n = n * 2
}
n // 128
var m = 2
do {
m = m * 2
} while m < 100
m // 128
在循环中使用range..或是初始化,条件,增量的形式来获得索引
123456789101112
var firstForLoop = 0
for i in 0..3 {
firstForLoop += i
}
firstForLoop // 3
var secondForLoop = 0
for var i = 0; i < 3; ++i {
secondForLoop += 1
}
secondForLoop // 3