Swift 入門指南 V1.00 - 單元 7 範例




CH07.playground


func doSomething1() {
    println("Hi")
}
doSomething1()

func doSomething2(a: Int) {
    println(a)
}
doSomething2(22)

func doSomething3(a: Int) -> Int {
    return a
}
doSomething3(12)

func doSomething4(a: Int, b: Int) -> Int {
    return a + b
}
doSomething4(23, 12)

func doSomething5(a: Int, b: Int) -> (Int, Int) {
    return (a + b, a - b)
}
doSomething5(22, 21)

func join1(str s1: String, mark m: String) -> String {
    return s1 + m
}
join1(str: "Hi", mark: ", ")

func join2(#s1: String, #m: String) -> String {
    return s1 + m
}
join2(s1: "Hi", m: ", ")

func join3(#s1: String, m: String = ", ") -> String {
    return s1 + m
}
join3(s1: "hello")
join3(s1: "Tom", m: "-")

func sum(numbers: Int...) -> Int {
    var total: Int = 0
    for n in numbers {
        total += n
    }
    
    return total
}
sum(1, 2, 3, 4, 5)
sum(11, 22, 33, 44, 55)

func mathFunction(f: (Int, Int) -> Int, a: Int, b: Int) {
    println("The result is \(f(a, b)).")
}
mathFunction(doSomething4, 12, 33)

the end

沒有留言: