Swift4--函数,自学笔记
函数
函数名
描述函数功能,调用函数时使用。
定义和调用函数
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--函数,自学笔记的更多相关文章
- Node.js自学笔记之回调函数
写在前面:如果你是一个前端程序员,你不懂得像PHP.Python或Ruby等动态编程语言,然后你想创建自己的服务,那么Node.js是一个非常好的选择.这段时间对node.js进行了简单的学习,在这里 ...
- 《Linux内核设计与实现》课本第四章自学笔记——20135203齐岳
<Linux内核设计与实现>课本第四章自学笔记 进程调度 By20135203齐岳 4.1 多任务 多任务操作系统就是能同时并发的交互执行多个进程的操作系统.多任务操作系统使多个进程处于堵 ...
- 《Linux内核设计与实现》课本第三章自学笔记——20135203齐岳
<Linux内核设计与实现>课本第三章自学笔记 进程管理 By20135203齐岳 进程 进程:处于执行期的程序.包括代码段和打开的文件.挂起的信号.内核内部数据.处理器状态一个或多个具有 ...
- 《Linux内核设计与实现》课本第十八章自学笔记——20135203齐岳
<Linux内核设计与实现>课本第十八章自学笔记 By20135203齐岳 通过打印来调试 printk()是内核提供的格式化打印函数,除了和C库提供的printf()函数功能相同外还有一 ...
- python自学笔记
python自学笔记 python自学笔记 1.输出 2.输入 3.零碎 4.数据结构 4.1 list 类比于java中的数组 4.2 tuple 元祖 5.条件判断和循环 5.1 条件判断 5.2 ...
- JavaScript高级程序设计之自学笔记(一)————Array类型
以下为自学笔记. 一.Array类型 创建数组的基本方式有两种: 1.1第一种是使用Array构造函数(可省略new操作符). 1.2第二种是使用数组字面量表示法. 二.数组的访问 2.1访问方法 在 ...
- JS自学笔记05
JS自学笔记05 1.例题 产生随机的16进制颜色 function getColor(){ var str="#"; var arr=["0","1 ...
- JS自学笔记04
JS自学笔记04 arguments[索引] 实参的值 1.对象 1)创建对象 ①调用系统的构造函数创建对象 var obj=new Object(); //添加属性.对象.名字=值; obj.nam ...
- JS自学笔记03
JS自学笔记03 1.函数练习: 如果函数所需参数为数组,在声明和定义时按照普通变量名书写参数列表,在编写函数体内容时体现其为一个数组即可,再传参时可以直接将具体的数组传进去 即 var max=ge ...
- JS自学笔记02
JS自学笔记02 1.复习 js是一门解释性语言,遇到一行代码就执行一行代码 2.查阅mdn web文档 3.提示用户输入并接收,相比之下,alert只有提示的作用: prompt(字符串) 接收: ...
随机推荐
- HighCharts之2D柱状图、折线图的组合多轴图
HighCharts之2D柱状图.折线图的组合多轴图 1.实例源码 SomeAxis.html: <!DOCTYPE html> <html> <head> < ...
- const char *p;和char * const p的区别
const char *p; const修饰*p,所以*p是一个常量,不可修改. char* const p; const修饰p,所以指针p是一个常量,不可修改. #include< ...
- Caused by: java.lang.ClassNotFoundException: com.mchange.v2.ser.Indirector
1.错误描述 usage: java org.apache.catalina.startup.Catalina [ -config {pathname} ] [ -nonaming ] { -help ...
- 【原】Java学习笔记031 - 常用类
package cn.temptation; public class Sample01 { public static void main(String[] args) { /* * 类 Math: ...
- CodeForces 940E
题意略. 这个题目我开始题意理解得有点问题.本题的实质是在这个数列中选择一些数字,使得选出的这些数字之和最大,用dp来解. 我们先要明确:当我选择数列长度为2 * c时,不如把这个长度为2 * c的劈 ...
- Java中使用UDP实现简单的聊天功能
通过DatagramSocket类来实现.此类表示用来发送和接收数据报包的套接字. 发送端代码如下: import java.io.IOException; import java.net.*; im ...
- CSS3盒子模型
web前端必须了解的CSS3盒子模型 1.需要了解的属性以及属性值 display:box或者display:inline-box box-orient:horizontal | vertical ( ...
- [Luogu4175][CTSC2008]网络管理Network
又是权限题qwq 一句话题意:带修改树上路径第k大 sol 数据结构?还是再见吧.学一手合格的整体二分,只有思维强大,才能见题拆题. 如果你做过整体二分的动态区间第k大就会发现这是一样的题. 无非是区 ...
- Android开发——设置界面的创建
前言: 最近忙着搞项目,难得有时间,便来整理搞项目中学习到的知识 使用之前,先介绍一下android这种的五种数据储存方式,分别为文件储存,SharePrefence,SQL,使用ContentPro ...
- 用Go自己实现配置文件热加载功能
说到配置文件热加载,这个功能在很多框架中都提供了,如beego,实现的效果就是当你修改文件后,会把你修改后的配置重新加载到配置文件中,而不用重启程序,这个功能在日常中还是非常实用的,毕竟很多时候,线上 ...