函数

  • 函数名

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

  • 定义和调用函数

    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. 个性化WinPE封装方法----制作过程需要了解的“命令”

    1.在现有的Windows7条件下,自动在E盘建立mywinpe文件夹,设置 Windows PE 构建环境,并保存到E:\mywinpe下 copype.cmd x86 E:\mywinpe 2.将 ...

  2. (十九)java小练习

    练习1:计算13-23+33-43+--+993-1003的结果     package demo; /**  * 计算13-23+33-43+--+993-1003的结果  * @author tu ...

  3. Exynos4412从SD卡启动的简单网络文件系统制作

    Exynos4412从SD卡启动的简单网络文件系统制作 1. 简介 嵌入式系统能够在开发板上正常运行,需要先进行系统配置,一个完整的嵌入式系统应该包含的几个部分::uboot,kernel,rootf ...

  4. java自带的类压缩和下载,以及递归删除动态的文件(shiro项目中来的十)

    详见项目,不用借助于任何外在的jar包,通过jre自带的实现.

  5. C#异常处理--C#基础

    try...catch:捕获异常try...finally:清除异常try..catch...finily:处理所有异常 1.捕获异常 using System; using System.Colle ...

  6. 四大组件之BroadcastReceiver基础

    1. 系统广播 1.1 动态注册   (1)创建自定义接收器类继承自BroadcaseReceiver,实现onReceive()方法,对接收到的广播的逻辑处理就是写在这个函数中的.   (2)实例化 ...

  7. 白话讲述Java中volatile关键字

    一.由一段代码引出的问题 首先我们先来看这样一段代码: public class VolatileThread implements Runnable{ private boolean flag = ...

  8. [BZOJ1601] [Usaco2008 Oct] 灌水 (kruskal)

    Description Farmer John已经决定把水灌到他的n(1<=n<=300)块农田,农田被数字1到n标记.把一块土地进行灌水有两种方法,从其他农田饮水,或者这块土地建造水库. ...

  9. C#利用substring按指定长度分割字符串

    这几天学习分析声音的波形数据,接收到的是十六进制的数据,需要将数据转换成十进制再绘图,这个过程涉及到字符串的分割,正好可以促进自己对C#相关知识的学习.说到分割字符串,我首先想到的是Split,但根据 ...

  10. ubuntu 14.04 下实现浏览器接收UDP视频流

    前言 由于近期项目需求,需实现在浏览器上实时预览接收UDP视频流信息.此功能若在VLC上可轻松播放,奈何由于Chrome.Firefox版本的升级,渐渐浏览器不支持外部插件,因而使用VLC web插件 ...