zoukankan      html  css  js  c++  java
  • 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")
    时光见证了成长,还很无知,我想一点点幼稚转为有知!
  • 相关阅读:
    部分和问题
    区间k大数训练
    蓝桥杯基础练习-数列排序
    蓝桥杯基础练习-特殊的回文数
    蓝桥杯基础练习-回文数
    蓝桥杯基础练习-特殊的数字
    蓝桥杯基础练习-杨辉三角
    蓝桥杯基础练习-查找整数
    蓝桥杯题库基础训练-数列特征
    三道半平面交测模板题 Poj1474 Poj 3335 Poj 3130
  • 原文地址:https://www.cnblogs.com/foreveriOS/p/5562976.html
Copyright © 2011-2022 走看看