swift的函数类型_001_swift函数类型基本使用

//: Playground - noun: a place where people can play

import UIKit

//-------函数类型-----------//
//每个函数都有一个类型,使用函数类型和其它的数据类型一样,可以定义变量或者常量它的数据类型为函数类型。

//1.函数类型的定义
func add(a:Int, b:Int) -> Int {
    return a + b;

}

func multiply(a:Int, b:Int) -> Int {
    
    return a * b;
}

//上面两个函数的类型是:(Int, Int) -> Int

func printHello() {
    print("Hello")
}
//这个函数的类型是 (Void) -> (Void)

//2.定义函数类型的变量或者常量
let a : Int = 0
var twoNumberFunc : (Int, Int) -> Int = add
//函数类型变量的定义: var 变量名:函数类型 = 对应的函数

//用函数类型的变量来调用函数
let result1 = twoNumberFunc(2, 3)

twoNumberFunc = multiply
let result2 = twoNumberFunc(2, 3)

//通过类型推导推导出函数类型变量的类型
let b = 3 //Int
let mySumFunc = add //(Int, Int) -> Int

//3.定义函数类型的函数参数
func doAthematics(mathFunc:(Int, Int) -> Int, a:Int, b:Int) -> Int {
    
    return mathFunc(a, b)
    
    
}

doAthematics(add, a: 2, b: 4)
doAthematics(multiply, a: 2, b: 4)


//4.函数类型作为返回值类型
//(Int)-> Int
func forward(input:Int) -> Int {
    
    return input + 1
}

func backward(input:Int) -> Int {
    
    return input - 1
}

//这个函数的返回值为函数类型
func choose(choice:Bool) -> (Int) -> Int {
    
    return choice ? forward : backward
}

var result : (Int) -> Int = choose(true)
result(8)

//5.函数类型和嵌套函数配合使用
func buttonAction(tag:Int) -> (String, String) -> String {
    
    //定义两个嵌套函数,嵌套函数的函数类型为(String, String) -> String
    func login(name:String, passwd:String) -> String {
        
        return "登录操作"
    }
    
    func register(name:String, passwd:String) -> String {
        
        return "注册操作"
    }
    
    if tag == 100 {
        
        return login
        
        
    } else {
        
        return register
        
    }
    
    
}

//验证
var buttonFunc = buttonAction(100)
buttonFunc("kathy", "123")
时光见证了成长,还很无知,我想一点点幼稚转为有知!
原文地址:https://www.cnblogs.com/foreveriOS/p/5562976.html