swift 函數(shù)與閉包

1.函數(shù)的定義與使用

//求兩個(gè)數(shù)之和的函數(shù)
//函數(shù)定義
//格式:func 函數(shù)名 (形參列表) -> 返回值類(lèi)型 { 函數(shù)體}
 func sum (number1:Int, number2:Int) -> Int{
     return number1 + number2;
 }
//函數(shù)的使用
let sumTwoNubmer = sum(2, number2: 3);

2.函數(shù)的形參的注意點(diǎn)
2.1默認(rèn)形參是常量,若要在函數(shù)中對(duì)形參改變,在形參前加上var修飾
2.2給參數(shù)添加一個(gè)名字,調(diào)用函數(shù)的時(shí)候就一目了然

func sum (numberone number1:Int,numbertwo number2:Int) ->Int {
    
    return number1 + number2;
}

let sum1 = sum(numberone: 1, numbertwo: 3)
print(sum1)

2.3形參的址傳遞:用inout 修飾形參,調(diào)用的時(shí)候用&

func test1 (inout number: Int) -> Int {
    number++
    return number;
}
var addtestNumber = 10;
let addnum = test1(&addtestNumber);    //結(jié)果:11
print(addnum)              //結(jié)果:11
print(addtestNumber)    //結(jié)果:11

2.4不定參數(shù)函數(shù)
說(shuō)明:形參的個(gè)數(shù)是不定的,但是形參的類(lèi)型必須是相同的,不定個(gè)數(shù)的形參實(shí)際上是一個(gè)數(shù)組


1451876890323984.png

2.5默認(rèn)形參:每個(gè)參數(shù)都是有名字的,調(diào)用函數(shù)的時(shí)候,可以給任意一個(gè)參數(shù)賦值,其他的就去默認(rèn)值

func love (name1:String = "山伯",name2: String = "英臺(tái)") {   
    print("\(name1) love \(name2)")
}
love()
love("梁山伯")
love("梁山伯", name2: "祝英臺(tái)")

3.函數(shù)類(lèi)型:如果幾個(gè)函數(shù)參數(shù)列表相同以及返回值類(lèi)型相同,那么這兩個(gè)函數(shù)就有著相同的函數(shù)類(lèi)型。

//定義枚舉
enum  Type: Int{
    case jia = 0
    case cheng
}

//3.函數(shù)類(lèi)型
func jia (n1: Int,n2: Int) -> Int{
    return n1 + n2;
}
func cheng (n1: Int,n2: Int) -> Int{
    return n1 * n2;
}


func typeName(type:Type) -> ((Int,Int) -> Int) {
    
    var myfunc: (Int,Int) -> Int
    
    switch type {
        
    case .jia:
        myfunc = jia
        
    case .cheng:
        myfunc = cheng
    }
    return myfunc
}

var myfunc: (Int,Int) -> Int
myfunc = typeName(Type.cheng)
print(myfunc(1,2))

myfunc = typeName(Type.jia)
print(myfunc(1,2))

4.函數(shù)嵌套

func typeName(type:Type) -> ((Int,Int) -> Int) {    
    func jia (n1: Int,n2: Int) -> Int{
        return n1 + n2;
    }
    func cheng (n1: Int,n2: Int) -> Int{
        return n1 * n2;
    }
    var myfunc: (Int,Int) -> Int
    switch type {       
    case .jia:
        myfunc = jia        
    case .cheng:
        myfunc = cheng
    }
    return myfunc
}

5.閉包:等同于OC中的block
5.1定義

var myCloure0:((Int, Int) -> Int)?
//或者
typealias MyClosureType = (Int, Int) -> Int
var myCloure:MyClosureType?

5.2應(yīng)用
說(shuō)明:A控制器有兩個(gè)控件,Lable和按鈕,B控制器有三個(gè)控件,textfield和倆按鈕,點(diǎn)擊A按鈕進(jìn)入B控制器,在B控制的textfield中輸入字符串,點(diǎn)擊確定按鈕把textfield中的字符串在A控制器的lable中顯示,或者點(diǎn)擊返回按鈕直接返回

//A控制器--ViewController
//  Created by Vanessa on 16/3/29.
//  Copyright ? 2016年 Vanessa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    var showLable: UILabel?
    var pushBtn: UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //1. 添加lable控件
        showLable = UILabel.init(frame: CGRectMake((UIScreen.mainScreen().bounds.size.width - 200) * 0.5, 100, 200, 44))
        showLable?.backgroundColor = UIColor.blueColor()
        self.view.addSubview(showLable!)
        
        //2. 添加按鈕控件
        pushBtn = UIButton.init(type: UIButtonType.Custom)
        pushBtn?.frame = CGRectMake((UIScreen.mainScreen().bounds.size.width - 200) * 0.5, 200, 200, 44)
        pushBtn?.backgroundColor = UIColor.grayColor()
        pushBtn?.setTitle("跳轉(zhuǎn)到下一界面", forState: UIControlState.Normal)
        pushBtn?.titleLabel?.textColor = UIColor.whiteColor()
        pushBtn?.addTarget(self, action: Selector.init(stringLiteral: "pushToSectionVC"), forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(pushBtn!)        
//        self.view.backgroundColor = UIColor.redColor()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    } 
  
//MARK: - event   
    func pushToSectionVC() {        
        let secVC: SecondViewController = SecondViewController()
        secVC.setMyblock {(str: String) -> Void in            
            self.showLable?.text = str
        }
        self.presentViewController(secVC, animated:true, completion: nil)       
    }
}
//B控制器--SecondViewController

import UIKit
class SecondViewController: UIViewController {
    
    var myBlock: ((str:String) -> Void)?
    var textField: UITextField?
    var backBtn: UIButton?
    var sureBtn: UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.view.backgroundColor = UIColor.whiteColor()
        
        textField = UITextField.init(frame: CGRectMake((UIScreen.mainScreen().bounds.size.width - 100) * 0.5, 100, 100, 44))
        textField?.backgroundColor = UIColor.greenColor()
        self.view.addSubview(textField!)
        
        backBtn = UIButton.init(frame: CGRectMake(50, 200, 60, 40))
        backBtn?.setTitle("返回", forState: UIControlState.Normal)
        backBtn?.backgroundColor = UIColor.blueColor()
        backBtn?.addTarget(self, action: Selector.init(stringLiteral: "back"), forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(backBtn!)
        
        sureBtn = UIButton.init(frame: CGRectMake(200, 200, 60, 40))
        sureBtn?.setTitle("確定", forState: UIControlState.Normal)
        sureBtn?.backgroundColor = UIColor.blueColor()
        sureBtn?.addTarget(self, action: Selector.init(stringLiteral: "sure"), forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(sureBtn!)        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
    func setMyblock(tempBlock: (str:String) -> Void) {
        self.myBlock = tempBlock
    }    
    //MARK: - event
    func back() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }    
    func sure() {
        if let string = textField?.text {
            myBlock!(str: (textField?.text!)!)
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }    
}

效果圖


viewController

SecondViewController

6.數(shù)組中常用的閉包函數(shù)
6.1映射(map)

let items = [1,2,3,4,5]
let strItems = items.map { (number: Int) -> String in
    return ("我是\(number)號(hào)")
}

6.2過(guò)濾器(Filter)

let score = [98,88,69,100,85,77]
let grade = score.filter { (score: Int) -> Bool in
    return score >= 85
}
print(grade) //[98, 88, 100, 85]

6.3Reduce

let totle = score.reduce(0) { (totleGrade: Int, everyGrade: Int) -> Int in
    return totleGrade + everyGrade
}
print(totle) //結(jié)果:517
totleGrade + everyGrade每次的運(yùn)算的結(jié)果曲線
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容