函数

  • 函数名

    描述函数功能,调用函数时使用。

  • 定义和调用函数

    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 12
    printWithoutCounting(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..<array.count] {
            if value < currentMin {
                currentMin = value
            } else if value > 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..<array.count] {
            if value < currentMin {
                currentMin = value
            } else if value > 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 6
    someFunction() // 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 numbers
    arithmeticMean(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 = 3
    var anotherInt = 107
    swapTwoInts(&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 = addTwoInts
    
    print("Result: \(mathFunction(2, 3))")
    // prints "Result: 5"
    
    mathFunction = multiplyTwoInts
    print("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 = 3
    let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
    // moveNearerToZero now refers to the stepBackward() function
    
    print("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 = -4
    let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
    // moveNearerToZero now refers to the nested stepForward() function
    while currentValue != 0 {
        print("\(currentValue)... ")
        currentValue = moveNearerToZero(currentValue)
    }
    print("zero!")
    // -4...
    // -3...
    // -2...
    // -1...
    // zero!

Swift4--函数,自学笔记的更多相关文章

  1. Node.js自学笔记之回调函数

    写在前面:如果你是一个前端程序员,你不懂得像PHP.Python或Ruby等动态编程语言,然后你想创建自己的服务,那么Node.js是一个非常好的选择.这段时间对node.js进行了简单的学习,在这里 ...

  2. 《Linux内核设计与实现》课本第四章自学笔记——20135203齐岳

    <Linux内核设计与实现>课本第四章自学笔记 进程调度 By20135203齐岳 4.1 多任务 多任务操作系统就是能同时并发的交互执行多个进程的操作系统.多任务操作系统使多个进程处于堵 ...

  3. 《Linux内核设计与实现》课本第三章自学笔记——20135203齐岳

    <Linux内核设计与实现>课本第三章自学笔记 进程管理 By20135203齐岳 进程 进程:处于执行期的程序.包括代码段和打开的文件.挂起的信号.内核内部数据.处理器状态一个或多个具有 ...

  4. 《Linux内核设计与实现》课本第十八章自学笔记——20135203齐岳

    <Linux内核设计与实现>课本第十八章自学笔记 By20135203齐岳 通过打印来调试 printk()是内核提供的格式化打印函数,除了和C库提供的printf()函数功能相同外还有一 ...

  5. python自学笔记

    python自学笔记 python自学笔记 1.输出 2.输入 3.零碎 4.数据结构 4.1 list 类比于java中的数组 4.2 tuple 元祖 5.条件判断和循环 5.1 条件判断 5.2 ...

  6. JavaScript高级程序设计之自学笔记(一)————Array类型

    以下为自学笔记. 一.Array类型 创建数组的基本方式有两种: 1.1第一种是使用Array构造函数(可省略new操作符). 1.2第二种是使用数组字面量表示法. 二.数组的访问 2.1访问方法 在 ...

  7. JS自学笔记05

    JS自学笔记05 1.例题 产生随机的16进制颜色 function getColor(){ var str="#"; var arr=["0","1 ...

  8. JS自学笔记04

    JS自学笔记04 arguments[索引] 实参的值 1.对象 1)创建对象 ①调用系统的构造函数创建对象 var obj=new Object(); //添加属性.对象.名字=值; obj.nam ...

  9. JS自学笔记03

    JS自学笔记03 1.函数练习: 如果函数所需参数为数组,在声明和定义时按照普通变量名书写参数列表,在编写函数体内容时体现其为一个数组即可,再传参时可以直接将具体的数组传进去 即 var max=ge ...

  10. JS自学笔记02

    JS自学笔记02 1.复习 js是一门解释性语言,遇到一行代码就执行一行代码 2.查阅mdn web文档 3.提示用户输入并接收,相比之下,alert只有提示的作用: prompt(字符串) 接收: ...

随机推荐

  1. arm上电死机怎么烧写boot

    一般上电到死机还有一段时间,在这段时间完成,已经出现两次了.

  2. JAVA之编码---->CSV在文本下是正常的,用EXCEL打开是乱码的问题

    JAVA之编码---->CSV在文本下是正常的,用EXCEL打开是乱码的问题 在JAVA下输出文件流,保存成CSV(用UTF-8)文件,怎么处理用EXCEL下是乱码,但是在记事本等其他软件都是正 ...

  3. 学习笔记:webpack深入与实践(一)

    一.webpack基本介绍 webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler). 四个核心概念: 入口(entry):指示 webpack 应该 ...

  4. json数据的转义

    { "DSGA": { "approval": "qatest_nj" }, "applydetailId": &quo ...

  5. Python Web-第三周-Networks and Sockets(Using Python to Access Web Data)

    1.Networked Programs 1.Internet 我们现在学习Internet部分,即平时我们浏览器做的事情,之后再学习客服端这部分 2.TCP 传输控制协议 3.Socket HTTP ...

  6. 配置maven环境出现ARP tomcat native library 版本安装跟需求版本不一致时的解决方法An incompatible version xxxx of the APR based Apache Tomcat Native library is installed, while Tomcat requires version xxxx

    此地址下载你所需要的library版本http://archive.apache.org/dist/tomcat/tomcat-connectors/native/ 点击binaries 点win32 ...

  7. MySQL入门笔记(二)

    MySQL的数据类型.数据库操作.针对单表的操作以及简单的记录操作可参考:MySQL入门笔记(一) 五.子查询   子查询可简单地理解为查询中的查询,即子查询外部必然还有一层查询,并且这里的查询并非仅 ...

  8. 【BZOJ2186】沙拉公主的困惑(数论)

    [BZOJ2186]沙拉公主的困惑(数论) 题面 BZOJ 题解 考虑答案是啥 先假设\(n=m\) 现在求的就是\(\varphi(m!)\) 但是现在\(n!\)是\(m!\)的若干倍 我们知道 ...

  9. 【BZOJ4816】数字表格(莫比乌斯反演)

    [BZOJ4816]数字表格(莫比乌斯反演) 题面 BZOJ 求 \[\prod_{i=1}^n\prod_{j=1}^mf[gcd(i,j)]\] 题解 忽然不知道这个要怎么表示... 就写成这样吧 ...

  10. [HNOI2013]游走

    题面在这里 题意 从1号点开始等概率选择路径并加上边权,直到到达n号点结束,要求将m条边赋权值1-m使得期望最小 sol 续上文 zsy ycb orz 简单的贪心:求出每条边的期望经过次数,sort ...