博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swift4 函数,例子代码
阅读量:5110 次
发布时间:2019-06-13

本文共 5119 字,大约阅读时间需要 17 分钟。

函数

苹果官方指南

苹果官方指南翻译

  • 函数名

    描述函数功能,调用函数时使用。
  • 定义和调用函数

    func greetAgain(person: String) -> String {    return "Hello again, " + person + "!"}print(greetAgain(person: "Anna"))// Prints "Hello again, Anna!"

    func 关键字,greetAgain 函数名,person 参数标签,String 参数类型,-> String 返回值及其类型, {} 函数功能代码,"Anna" 实际参数

    函数形式参数和返回值

  • 无形式参数的函数

    func sayHelloWorld() -> String {    return "hello, world"}print(sayHelloWorld())// prints "hello, world"
  • 多形式参数的函数

    func greet(person: String, alreadyGreeted: Bool) -> String {    if alreadyGreeted {        return greetAgain(person: person)    } else {        return greet(person: person)    }}print(greet(person: "Tim", alreadyGreeted: true))// Prints "Hello again, Tim!"
  • 无返回值的函数

    func printAndCount(string: String) -> Int {    print(string)    return string.characters.count}func printWithoutCounting(string: String) {    let _ = printAndCount(string: string)}printAndCount(string: "hello, world")// prints "hello, world" and returns a value of 12printWithoutCounting(string: "hello, world")// prints "hello, world" but does not return a value
    严格来说,无返回值函数返回了特殊值Void,如有返回值,需要处理返回值,不然函数出错。
  • 多返回值的函数

    func minMax(array: [Int]) -> (min: Int, max: Int) {    var currentMin = array[0]    var currentMax = array[0]    for value in array[1..
    currentMax { currentMax = value } } return (currentMin, currentMax)}let bounds = minMax(array: [8, -6, 2, 109, 3, 71])print("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..
    currentMax { currentMax = value } } return (currentMin, currentMax)}

    函数实际参数标签和形式参数名

  • 指定实际参数标签

    func greet(person: String, from hometown: String) -> String {    return "Hello \(person)!  Glad you could visit from \(hometown)."}print(greet(person: "Bill", from: "Cupertino"))// Prints "Hello Bill!  Glad you could visit from Cupertino."
  • 省略实际参数标枪

    func someFunction(_ firstParameterName: Int, secondParameterName: Int) {    // In the function body, firstParameterName and secondParameterName    // refer to the argument values for the first and second parameters.}someFunction(1, secondParameterName: 2)
    利用下划线( _ )来为这个形式参数代替显式的实际参数标签
  • 默认形式参数值

    func someFunction(parameterWithDefault: Int = 12) {    // In the function body, if no arguments are passed to the function    // call, the value of parameterWithDefault is 12.}someFunction(parameterWithDefault: 6) // parameterWithDefault is 6someFunction() // parameterWithDefault is 12
  • 可变的形式参数

    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 numbersarithmeticMean(3, 8.25, 18.75)// returns 10.0, which is the arithmetic mean of these three numbers
    形式参数的类型名称后边插入三个点符号( ...)来书写可变形式参数
  • 输入输出形式参数

    func swapTwoInts(_ a: inout Int, _ b: inout Int) {    let temporaryA = a    a = b    b = temporaryA}var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)print("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}var mathFunction: (Int, Int) -> Int = addTwoIntsprint("Result: \(mathFunction(2, 3))")// prints "Result: 5"mathFunction = multiplyTwoIntsprint("Result: \(mathFunction(2, 3))")// prints "Result: 6"
  • 函数类型作为形式参数类型

    func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {    print("Result: \(mathFunction(a, b))")}printMathResult(addTwoInts, 3, 5)// Prints "Result: 8"
  • 函数类型作为返回类型

    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 = 3let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)// moveNearerToZero now refers to the stepBackward() functionprint("Counting to zero:")// Counting to zero:while currentValue != 0 {    print("\(currentValue)... ")    currentValue = moveNearerToZero(currentValue)}print("zero!")// 3...// 2...// 1...// zero!
  • 内嵌函数

    func chooseStepFunction(backward: Bool) -> (Int) -> Int {    func stepForward(input: Int) -> Int { return input + 1 }    func stepBackward(input: Int) -> Int { return input - 1 }    return backward ? stepBackward : stepForward}var currentValue = -4let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)// moveNearerToZero now refers to the nested stepForward() functionwhile currentValue != 0 {    print("\(currentValue)... ")    currentValue = moveNearerToZero(currentValue)}print("zero!")// -4...// -3...// -2...// -1...// zero!

转载于:https://www.cnblogs.com/ccjoy/p/8658589.html

你可能感兴趣的文章
阅读代码分析工具Understand 2.0试用
查看>>
一次失败的项目经理招聘经验
查看>>
怎么保存退出vi编辑
查看>>
项目优化之热更新
查看>>
执行带返回参数的存储过程
查看>>
ECNUOJ 2616 游黄山
查看>>
Linux 查询配置命令
查看>>
存储过程入门
查看>>
Java泛型的基本使用
查看>>
我的游戏学习日志8——数字游戏策划(3)数字游戏的概念
查看>>
智力逻辑题
查看>>
Phpcms V9导航循环下拉菜单的调用技巧
查看>>
SpringBoot前后端分离Instant时间戳自定义解析
查看>>
开发一个简单的 Vue 弹窗组件
查看>>
1076 Wifi密码 (15 分)
查看>>
rsync
查看>>
java中的IO操作总结
查看>>
noip模拟赛 党
查看>>
bzoj2038 [2009国家集训队]小Z的袜子(hose)
查看>>
Java反射机制及其Class类浅析
查看>>