Swift基础03

来源:互联网 发布:mac os x安装盘下载 编辑:程序博客网 时间:2024/05/18 23:12

Swift基础03

函数和闭包


函数的定义和调用

// 1. 没有参数,没有返回值的函数func method1() {    print("老王,我终于开始学函数啦,好高兴啊")}method1() //函数的调用
//2. 有参数,没返回值//注意参数一定要指明数据类型;如果有多个参数,就用 , 隔开//没有返回值其实是说,它的返回值为()或者 Voidfunc method2(param: String, param1: String) {    print("老王,我终于开始学\(param)啦,好\(param1)啊")}method2("函数", param1: "蒙 b")
//3. 有参数,有返回值//a. 返回值写返回值的数据类型//b. 如果有返回值,必须 returnfunc method3(param: String, param1: String) ->String { //返回值类型为String类型    print("老王啊,我终于开始学\(param)啦,好\(param1)啊")    return "老王啊,我终于开始学\(param)啦,好\(param1)啊"}let method3Str = method3("函数", param1: "高兴")

函数的参数

  • 函数有一个内部参数名(形参本身),和一个外部参数名。内部参数名,直接参与运算。而外部参数名,它是对内部参数名的一个说明和解释
  • swift 默认从第二个参数开始。为参数添加了一个和形参一样的外部参数名。第一个参数没有外部参数名
  • 我们可以自已定义外部参数名,如果自己定义了外部参数名,则外部参数名必须写
  • 如果我们不想要外部参数名,可以用一个 _ 可以忽略外部参数名,_ 放在外部参数名的位置
func sum(firstNum a: Int,SecondNum b: Int) -> Int { //给两个形参添加外部参数名(firstNum,SecondNum)    return a + b}sum(firstNum: 5, SecondNum: 5) //调用函数时需写上外部参数名//sum(5, b: 5)func sum1(a: Int,_ b: Int) -> Int { //不需要外部参数名,用 _ 代替    return a + b}sum1(5, 5)

函数的类型

  • 函数的类型,就是参数和返回值的组合体
//以下函数的类型为:(a: Int, b: Int)-> Intfunc sum(a: Int, b: Int)-> Int {    return a + b}typealias funcType = (a: Int, b: Int) -> Int //给函数的类型起别名为funcTypelet method:funcType  = sum //函数可以像普通类型那样赋值method(a: 5, b: 5)//2. 函数作为参数传递func time(a: Int, b: Int)->Int {    return a * b}func caculator (a: Int, b: Int,math :funcType)->Int { //函数的形参是一个函数类型    return math(a: a, b: b)}caculator(5, b: 5, math: sum) //传递不同的函数,执行不同的操作caculator(5, b: 5, math: time)//3. 函数做为返回值返回//函数可能嵌套定义func caculator2(age: Int)->(Int, Int) -> Int{ //返回的结果是函数类型,以第一个'->'为准    func sum(a: Int, b: Int)-> Int {        return a + b    }    func time(a: Int, b: Int)->Int {        return a * b    }    return age > 5 ? time : sum}let mathMethod = caculator2(10)mathMethod(5, 5)let mathMethod2 = caculator2(2)mathMethod2(5, 5)

闭包的定义

  • 闭包是一个有名字的函数代码块
  • 闭包被完整地包裹在{}里面
//1. 建一个没有参数,也没有返回值的函数func method() {    print("啊,我开始学闭包啦")}method()//定义了一个没有参数也没有返回值的闭包let clousure = {    print("啊,我开始学闭包啦")}clousure() //调用闭包
//2. 建一个有参数,没有返回值的函数func method2(a: Int, b: Int) {    print(a + b)}method2(5, b: 5)//建了一个有参数没有返回值的闭包let clousure2 = {    (a: Int, b: Int) in //in前面的表示参数,后面的是闭包要执行的操作    print(a + b)}clousure2(5, 10)
//3. 建一个有参数,有返回值的函数func method3(a: Int, b: Int)->Int {    return a + b}let result = method3(5, b:10)//定义了一个有参数,有返回值的闭包let clousure3 = {    (a: Int, b: Int)->Int in  //in前面表示参数和返回值,后面的是闭包要执行的操作    return a + b }let result2 = clousure3(5, 10)
0 0
原创粉丝点击