Swift-6-函数

// Playground - noun: a place where people can play

import UIKit

// 定义和调用函数
func sayHello(personName : String) -> String {
    let greeting = "hello, " + personName + "!"
    
    return greeting
}

println(sayHello("Anna"))

// 方法参数与返回值
// 1. 多个参数
func halfOpenRangeLength(start : Int, endRange end : Int) -> Int {
    return end - start
}

println(halfOpenRangeLength(1, endRange: 10))

// 2. 无参数
func sayHelloWorld() -> String {
    return "hello, world"
}

println(sayHelloWorld())

// 3. 无返回值
func sayGoodbye(personName: String) -> Void {
    println("goodbye, \(personName)!")
}
//func sayGoodbye(personName: String) {
//    println("goodbye, \(personName)!")
//}
//func sayGoodbye(personName: String) -> () {
//    println("goodbye, \(personName)!")
//}
sayGoodbye("Anna")

// 4. 多个返回值
func queryTupleReturnValue() -> (first : Int, second : Int) {
    return (1, 3)
}

let bounds = queryTupleReturnValue()
println("first is \(bounds.first), second is \(bounds.second)")

// 5. 返回多个可选值[整体可选,非单个元素是optional]
func optionalTupleValue() -> (first : Int, second : Int)? {
    return (2, 4)
}

if let optionalTuple = optionalTupleValue() {
    println("optional: first is \(optionalTuple.first), second is \(optionalTuple.second)")
}

// 方法参数名
// 1. 外部参数名[目的是调用方法时可以更加清晰的看到每个参数的作用]
func join(string s1 : String, toString s2: String, withJoiner joiner : String) -> String {
    return s1 + joiner + s2
}

join(string: "hello", toString: "world", withJoiner: ",") // 每一个参数的涵义更加明确

// 2. 标记外部参数名和参数名一致 #
func containsCharacter(#string : String, #characterToFind : Character) -> Bool {
    for character in string {
        if character == characterToFind {
            return true
        }
    }
    return false
}

containsCharacter(string: "fsafh", characterToFind: "s")

// 3. 参数默认值[为参数指定默认值,在调用方法时可以忽略该参数]
func joinWithDefaultJoiner(string s1 : String, toString s2 : String, withJoiner joiner : String = " ") -> String {
    return s1 + joiner + s2
}
joinWithDefaultJoiner(string: "hello", toString: "world", withJoiner: ",")
joinWithDefaultJoiner(string: "hello", toString: "world")

// 4. 有默认值参数的外部参数名[为了清晰的看到已有默认值的参数在方法调用时调用者是否提供了值,swift会自动为友默认值的参数生成外部参数名,相当于在参数名前默认添加 #]
func joinWithAutoExternalName(s1 : String, s2 : String, joiner : String = " ") -> String {
    return s1 + joiner + s2
}

joinWithAutoExternalName("hello", "world", joiner: "-")

// 5. 可变形参[参数在方法内部相当于array,类型由形参类型决定]
func arithmeticMean(numbers : Double...) -> Double {
    var total : Double = 0
    for number in numbers {
        total += number
    }
    
    return total / Double(numbers.count)
}

arithmeticMean(1, 3, 5, 8, 10) // numbers 相当于 [1, 3, 5, 8, 10]
// 注意: 一个方法里最多只能存在一个变长参数,并且应该被放在参数列表的最后面

// 6. 常量和变量参数[默认情况下,方法内的参数都是常量(let),无法在方法内部进行改变。 使用var定义可变参数]
func modifyParameter(var string : String) -> String {
    string += "-modified" // 试图修改使用默认let的参数会报错
    return string
}

modifyParameter("hello")

// 7. 方法内修改外部变量
func modifyOutVar(inout string : String) -> String {
    string += "modified by func"
    return string
}

var string = "to modify"
modifyOutVar(&string)
println("modify: \(string)")
// 注意: 1.in-out 参数不能设置默认值 2.变长参数不能成为in-out参数 3.in-out参数不能使用let或者var 4. 传入in-out参数时,传的是地址

// 方法类型
func addTwoInts(a : Int, b : Int) -> Int {
    return a + b
}
// 上面方法类型为 (Int, Int) -> Int
func printHelloWorld() {
    println("hello, world")
}
// 上面方法类型为 () -> () 或者 () -> Void

// 1. 使用方法类型
var mathFunction : (Int, Int) -> Int = addTwoInts
mathFunction(2, 3)

// 2. 方法类型作为参数
func printMathResult(mathFunction : (Int, Int) -> Int, a : Int, b : Int) {
    let result = mathFunction(a, b)
    println("result:\(result)")
}

printMathResult(mathFunction, 3, 13)

// 3. 方法类型作为返回值
func stepForward(input : Int) -> Int {
    return input + 1
}

func stepBackward(input : Int) -> Int {
    return input - 1
}

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
    return backwards ? stepBackward : stepForward
}

// 调用
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
while currentValue != 0 {
    println("currentvalue: \(currentValue)")
    currentValue = moveNearerToZero(currentValue)
}
println("zero")

// 4. 嵌套函数
func anotherChooseStepFunction(backwards: Bool) -> (Int) -> Int {
    
    func stepForward(input : Int) -> Int {
        return input + 1
    }
    
    func stepBackward(input : Int) -> Int {
        return input - 1
    }
    return backwards ? stepBackward : stepForward // 使用与前面一样
}

 

posted @ 2014-11-23 18:27  2020_xx  阅读(192)  评论(0编辑  收藏  举报