7.函数

作者: LucXion | 来源:发表于2021-07-14 09:52 被阅读0次

参数标签、参数名称

// 合理利用标签和名称,可以增加可读性,代码更接近自然语言
/*
 参数标签(外部参数):from
 参数名称(内部参数):hometown
 */
func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))

参数设置默认值

习惯上,无默认值得参数放前面,因为它们比较重要

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    // 如果你在调用时候不传第二个参数,parameterWithDefault 会值为 12 传入到函数体中。
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault = 12

可变参数

// 一个函数只允许存在一个数量可变的参数
func sum(nums:Int...)->Int{
    var count = 0
    for item in nums {
        count += item
    }
    return count
}

输入输出参数:函数内修改传入的外部参数的值,对函数体外产生影响的一种方式

var a = 10,b = 20
func changeValue(_ a:inout Int,_ b:inout Int){
    let temp = a
    a = b
    b = temp
}
changeValue(&a, &b)
// inout ,&,inout参数不能设置默认值
// 不能传 常量 和 字面量

函数可以作为参数或者返回值

var arr = [1,2,3,5,4]
// 系统api将函数作为参数的实例:arr.sort(by: (Int, Int) throws -> Bool)

函数嵌套、局部函数

// 根据条件选择函数
func choseFunction(back:Bool)->(Int)->Int{
    let f:(Int)->Int
    if back {
        func add(num: Int)->Int{return num + 1}
        f = add
    }else {
        func sub(num:Int)->Int{return num - 1}
        f = sub
    }
    // 传递函数给外部调用
    return f
}
var num = 4
let f = choseFunction(back: num < 0)
while num != 0 {
    print(num)
    num = f(num)
}

相关文章

  • 7. 函数

    基于网络课程《Python全栈开发专题》 记录笔记,请支持正版课程。 斐波那契数列 斐波那契数列科普:https:...

  • 7. 函数

    Python内置的常用函数还包括数据类型转换函数,比如int()函数可以把其他数据类型转换为整数 函数名其实就是指...

  • 7.函数

    课程来自慕课网DavidChin老师 函数 函数的调用 函数的默认参数

  • 7.函数

    参数标签、参数名称 参数设置默认值 习惯上,无默认值得参数放前面,因为它们比较重要 可变参数 输入输出参数:函数内...

  • 数据团Python_7. 函数

    7. 函数 7.1 函数概念及常用函数调用 函数,完成某个工作的代码块,由语句构成函数组成: 函数名称 函数参数 ...

  • Scala入门与进阶(六)- Scala 函数高级操作

    7. Scala 函数高级操作 1. 字符串高级操作 2. 匿名函数 3. currying 函数

  • GeekBand C++面向对象高级编程(上) 笔记&心得 2(

    7.三大构造函数:拷贝构造,拷贝赋值,析构函数 Class With Pointer member(s) :要写析...

  • 第5天 PHP函数与递归

    7. 函数 7.1. 函数的概念与作用 var_dump() 、sqrt()、floor() 、ceil() 在P...

  • R数据科学--使用ggplot2进行数据可视化2

    7.统计变换 (1)diamonds数据集 (2)统计变换函数和几何对象函数 用统计变换函数stat_count做...

  • AutoLisp中常见的函数(2)

    6. 等待输入函数 7. 几何运算函数 8. 对象处理函数 9. 选择集、符号表处理函数 10. AutoCAD相...

网友评论

      本文标题:7.函数

      本文链接:https://www.haomeiwen.com/subject/bbgrpltx.html