Swift(十二)函数

Swift(十二)函数_第1张图片
cb93fae52cfe06865b76627aef54e9f3b908644d147987-KoTrU6_fw658.jpeg

函数的定义

//sayHello函数名, personName为参数, -> 表示返回值
func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "! "
    return greeting
}

1.多个参数

func halfOpenRangeLength(start: Int, end: Int) -> Int {
    return end - start
}
print(halfOpenRangeLength(start: 1, end: 10))

2.无参函数

func sayHelloWorld() -> String {
    return "hello, world"
}
print(sayHelloWorld())
// prints "hello, world"

尽管这个函数没有参数,但是定义的时候,函数名后面还是需要一对圆括号。无参函数被调用时,在函数名后面也需要一对圆括号。

3.无返回值函数

 func sayGoodbye(personName: String) {
    print("Goodbye, \(personName)! ")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave! "

如果函数没有返回值,函数的定义中不需要 箭头(->)和返回类型。

多个返回值函数

func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
    var vowels = 0, consonants = 0, others = 0
    for character in string.characters {
        switch String(character).lowercased() {
        case "a", "e", "i", "o", "u":
            vowels += 1
        case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
             "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
            consonants += 1
        default:
            others += 1
        }
    }
    return (vowels, consonants, others)
}
let total = count(string: "some arbitrary string! ")
print("\(total.vowels) vowels and \(total.consonants) consonants")

使用元组(tuple)类型组合多个值为一个复合值作为函数的返回值。

参数默认值

func append(string: String = "-") -> String {
    return string + "abc"
}
append() //-abc ,参数没有赋值, 则使用默认参数
append(string: "qq") //qqabc //参数赋值, 则使用赋值的参数

可变参数

func countStr(nums:Double...) ->Double {
    var result = 0.0
    for num in nums {
        result += num
    }
    return result
}
countStr(nums: 1, 2, 3)

注意:一个函数最多只能由一个可变参数,它必须是参数列表的最后的一个。这样做是为了避免函数调用时出现歧义。

常量和变量参数#

func aliginRight(var string: String) {
  //在swift3.0中, 测试发现错误, 3.0中已经取消了这种写法, 不能这样定义变量参数
//error: parameters may not have the 'var' specifier
//func aliginRight(var string: String) {
                 ^~~

}

输入输出参数

简单来说, 就是在函数体内, 通过修改传入的参数的值, 达到修改函数外部变量的效果

//定义一个方法, 用于交换传入的两个参数的值
//使用inout关键字
func modify(s1: inout String) {
    s1 = "modify"
}

var string = "string"
modify(s1: &string)
print(string) //"modify"

通过在参数前加 inout 关键字定义一个输入输出参数。输入输出参数值被传入函数,被函数修改,然后再被传出函数,原来的值将被替换。

只能传入一个变量作为输入输出参数。不能传入常量或者字面量(literal value),因为这些值是不允许被修改的。当传入的实参作为输入输出参数时,需要在实参前加 & 符,表示这个值可以被函数修改。
从上面这个例子,可以看到 string原始值在 modify 函数中已经被修改了,尽管它们定义在函数体外。

注意:输入输出参数和返回值是不一样的。函数 modify 没有定义返回值,却修改了 string值。输入输出参数是函数对函数体外产生影响的另一种方式。

使用函数类型

func one(a: Int, b: Int) ->Int {
    return a + b
}
//把一个函数赋值给一个变量
var mathFunction: (Int, Int) -> Int = one
//如果是直接使用函数名调用, 需要形参
one(a: 1, b: 3)
//如果使用赋值的函数变量, 则不需要形参
mathFunction(1, 2)

函数作为参数

func one(a: Int, b: Int) ->Int {
    return a + b
}
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
//调用one函数
    print("Result: \(mathFunction(a, b) + a + b)")
}
//把函数传进来
printMathResult(mathFunction: one, a: 3, b: 5)

函数作为返回值

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

//该函数有一个布尔值的参数backwards和一个返回值, 返回值是一个函数, (该函数有一个参数为Int类型,返回值是Int类型)
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
    return backwards ? stepBackward : stepForward
}

let moveNearerToZero = chooseStepFunction(backwards: false)
// moveNearerToZero 现在代表的就是 stepBackward() 函数
print(moveNearerToZero(1)) //2

嵌套函数

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

在这章中的所有函数都是全局函数(global functions),因为它们定义在全局域中。
当然函数也可以被定义在别的函数体中,称作嵌套函数(nested functions)。

默认情况下,嵌套函数是对外是不可见的,但可以被封闭他们的函数(enclosing function)调用。封闭函数可以返回它的一个嵌套函数,使这个函数在其他域中可以被使用。

你可能感兴趣的:(Swift(十二)函数)