Swift Tour 随笔总结 (4)

Switch的一个例子:

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 agood tea sandwich."

case let x where  x.hasSuffix("pepper"):

    let vegetableComment = "Is it a spicy \(x)?"

default:

    let vegetableComment = "Everything tastes good in soup."

}

比起传统的oc有一些新特性,接受了就好挺实用的

不用break

for的拓展

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

        }

    }

}

largest

while/do while保持一致

其他for的拓展用法

var firstForLoop = 0

for i in 0..3{

firstForLoop += i

}

firstForLoop



var secondForLoop = 0

for var i = 0; i < 3; ++i {

    secondForLoop += 1

}

secondForLoop

使用 … 代替 .. 则包含upper value(<和<=的差别)

Functions and Closures

func greet(name: String, day: String) -> String {

    returrn "Hellop \(name), today is \(day)."

}

greet("Bob", "Tuesday")



//使用tuple来返回多个值

func getGasPrices() -> (Double, Double, Double) {

    return (3.59, 3.69, 3.79)

}

getGasPrices()

func会使用数组收集多个变量:

func sumOf(numbers: Int...) -> Int {

    var sum = 0

    for number in numbers {

        sum += number

    }

    return sum

}

sumOf()

sumOf(42, 597, 12)

函数的下次接着写吧,挺多的T T

你可能感兴趣的:(swift)