Swift(二)流程控制

2017-01-14 15:50:21来源:http://www.jianshu.com/p/c19b8eb6e65f作者:里脊糖醋人点击



5227f560d999a433a2daad3147251ee207625d49382ce-1umldo_fw658.jpeg
var optionalName: String? = "John Appleseed"
optionalName = nil
var greeting = "Hello! "
//判断optionalName 是否为nil
if let name = optionalName {
greeting = "Hello, /(name)"
}else {
print(greeting);
}

let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
print(vegetableComment)
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
print(vegetableComment)
//次初需要注意, let ... where ... 意思是根据参数进行额外的条件, 意思就是x是否以pepper结尾
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy /(x)?"
print(vegetableComment)
default:
let vegetableComment = "Everything tastes good in soup."
print(vegetableComment)
}

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
//如果注释print(key), 则会提示Immutable value 'key' never used, 建议你使用'_'替换, 如果你和我一样是一个追求完美的人, 有强迫症, 那就替换掉, 如果没有强迫症, 不替换也没事
//在swift里面, 如果你声明一个变量, 如果你没有使用它, 会提醒你把变量声明为常量let, 如果在let下, 你还没有使用它,Initialization of immutable value 'x' was never used, 希望你使用'_'替换
for (key, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
//print(key)
}
}
}
print(largest)

//此数需要注意, For循环的写法和swift2有所区别
//..两个点不包括上界
var firstForLoop = 0
for i in 0..<3 {
firstForLoop += i
print("-----")
}
print(firstForLoop)
//三个点包括上界
var secondForLoop = 0
for _ in 0 ... 3 {
secondForLoop += 1
print("++++++")
}
print(secondForLoop)

        //反转
for i in (1...10).reversed() {
print(i)
}
//不包括10
for i in stride(from: 0, to: 10, by: 2) {
print(i)
}
//包括10
for i in stride(from: 0, through: 10, by: 2) {
print(i)
}

//Swift语言中, 判断条件必须是一个表达式, 这和Objective-C 中不同, 在OC中, 字需要是一个非0的值就可以了.
let i = 1
if i {
// this example will not compile, and will report an error
}



最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台