Swift学习笔记(四)函数

定义和调用函数 参数名personName,参数类型String 返回值类型是String

func sayHello(personName: String) -> String{
    let greeting = "hello, " + personName + "!"
    return greeting;
}
println(sayHello("John"))

func halfOpenRangeLength(start: Int, end: Int) -> Int {
    return end - start
}
println(halfOpenRangeLength(1, 10))
// prints "9"

函数的多返回值元组(此处的返回值声明了变量名:方便调用函数时可以使用变量名获取值)

func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}

let bounds = minMax([8, -6, 2, 109, 3, 71])
println("min is \(bounds.min) and max is \(bounds.max)")
// prints "min is -6 and max is 109"

函数的可选元组返回类型

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty { return nil }
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}
if let bounds = minMax([8, -6, 2, 109, 3, 71]) {
    println("min is \(bounds.min) and max is \(bounds.max)")
}
// prints "min is -6 and max is 109"

函数的参数名:本地参数名和外部参数名
一、本地参数名:本地参数名就是定义函数名时,在参数列表中所写的参数名,它只能在函数主体内使用

二、外部参数名:帮助理解参数的目的,更好的表达参数的功能,就需要在定义时使用外部参数名,外部参数名需要卸载本地参数名之前,并使用空格将其分开

三、如果调用时使用外部参数,则在调用该函数时需要使用外部参数名
*外部参数名不能在函数主体内使用
*如果开发者想为函数的参数提供一个外部参数名,而本地参数名已经使用了一个合适的名称,这时就不需要再为该函数写相同的两次名称了,取而代之,写一次名称,并用”#”号作为名称的前缀

func someFunction(parameterName: Int) {
   //parameterName是本地参数名
   //调用时不写参数名
}

func someFunction(externalParameterName localParameterName: Int) {
   //externalParameterName是外部参数名  
   //localParameterName是本地参数名 
   //调用时需要写外部参数名
}

func someFunction(#localParameterName: Int) {
   //#用来标识参数即是本地参数名又是外部参数名
}
someFunction(2)
someFunction(externalParameterName: 2)
someFunction(localParameterName: 2)

设置函数参数的默认参数值(调用时传值了,则使用传的值,否则使用默认值)

func join(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String {
    return s1 + joiner + s2
}

join(string: "hello", toString: "world", withJoiner: "-")
// returns "hello-world"
join(string: "hello", toString: "world")
// returns "hello world"

可变参数:使一个参数接受0个或多个指定类型的值,设定一个可变参数需要在参数类型名添加”…”
一个函数中只能有一个可变参数,且可变参数的位置必须是所有的之后

func arithmeticMean(numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers

常量参数和变量参数
函数的参数默认都是let常量,如果尝试去改变参数的值就会出现编译错误
如果想要在函数主体内对参数进行修改,你可以使用变量参数,即在参数名前加”var”关键字
变量参数的作用范围是在整个函数体内

func alignRight(var string: String, count: Int, pad: Character) -> String {
//    let stringCount = count(string)
    let amountToPad = count - 5
    if amountToPad < 1 {
        return string
    }
    let padString = String(pad)
    for _ in 1...amountToPad {
        string = padString + string
    }
    println(string)
    return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, "-")
// paddedString is equal to "-----hello"
// originalString is still equal to "hello"

输入输出参数:
如果你想修改一个参数值,并且在函数调用之后仍然有效,这时就可以使用输入输出参数
在参数名前加”inout”关键字来定义输入输出参数
输入输出参数不能有默认值
当你使用了inout修饰时就不能再使用var或者let
调用时,必须在参数前加”&”符号

func swapTwoInts(inout #a: Int, inout #b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(a: &someInt, b: &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"

函数类型
每一个函数都有一个特定的函数类型,由参数类型和返回值类型共同决定

func addTwoInts(a: Int, b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(a: Int, b: Int) -> Int {
    return a * b
}
//上面两个函数的类型都是 (Int, Int) -> Int

函数类型的使用:定义一个变量mathFunction,其是一个函数类型,指向addTwoInts函数

var mathFunction: (Int, Int) -> Int = addTwoInts
println("Result: \(mathFunction(2, 3))")

与其他类型一样,当你为一个常量或变量分配一个函数时,你可以把它推断函数类型

let anotherMathFunction = mathFunction

函数类型做参数类型
当函数的提供者提供的函数被调用时,会使你脱离了一个函数某些方面的具体实现
如下示例:addTwoInts,3,5做参数,当调用mathFunction(a, b),实际上会调用addTwoInts(3,5)
这就使得开发者本身不用关系addTwoInts的实现

func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
    println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8"

函数类型做返回值类型
stepForward和stepBackward的函数类型都是(Int) -> Int

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

chooseStepFunction的返回值类型是函数类型(Int) -> Int

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

var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function
moveNearerToZero(10)
//prints "9"

嵌套函数
嵌套函数默认情况下对外界是隐藏的,但是仍然可以调用和使用其内部的函数
内部函数也可以返回一个嵌套函数,允许在嵌套函数内的另一个范围内使用。

func chooseStepFunction2(backwards: Bool) -> (Int) -> Int {

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

    func stepBackward(input: Int) -> Int {
        return input - 1
    }
    return backwards ? stepBackward : stepForward
}
var currentValue2 = -4
let moveNearerToZero2 = chooseStepFunction2(currentValue2 > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue2 != 0 {
    print("\(currentValue2), ")
    currentValue2 = moveNearerToZero2(currentValue2)
}
println("zero!")
// -4, -3, -2, -1, zero!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值