美文网首页
swift 函数与闭包

swift 函数与闭包

作者: 维子Vanessa | 来源:发表于2016-03-29 17:54 被阅读64次

1.函数的定义与使用

//求两个数之和的函数
//函数定义
//格式:func 函数名 (形参列表) -> 返回值类型 { 函数体}
 func sum (number1:Int, number2:Int) -> Int{
     return number1 + number2;
 }
//函数的使用
let sumTwoNubmer = sum(2, number2: 3);

2.函数的形参的注意点
2.1默认形参是常量,若要在函数中对形参改变,在形参前加上var修饰
2.2给参数添加一个名字,调用函数的时候就一目了然

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

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

2.3形参的址传递:用inout 修饰形参,调用的时候用&

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

2.4不定参数函数
说明:形参的个数是不定的,但是形参的类型必须是相同的,不定个数的形参实际上是一个数组


1451876890323984.png

2.5默认形参:每个参数都是有名字的,调用函数的时候,可以给任意一个参数赋值,其他的就去默认值

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

3.函数类型:如果几个函数参数列表相同以及返回值类型相同,那么这两个函数就有着相同的函数类型。

//定义枚举
enum  Type: Int{
    case jia = 0
    case cheng
}

//3.函数类型
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.函数嵌套

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应用
说明:A控制器有两个控件,Lable和按钮,B控制器有三个控件,textfield和俩按钮,点击A按钮进入B控制器,在B控制的textfield中输入字符串,点击确定按钮把textfield中的字符串在A控制器的lable中显示,或者点击返回按钮直接返回

//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("跳转到下一界面", 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.数组中常用的闭包函数
6.1映射(map)

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

6.2过滤器(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) //结果:517
totleGrade + everyGrade每次的运算的结果曲线

相关文章

  • Swift学习笔记(1)

    SWift学习笔记 闭包 闭包表达式 闭包是自包含的函数代码块,可以在代码中被传递和使用。Swift 中的闭包与 ...

  • swift学习笔记 ⑥ —— 闭包

    Swift学习笔记 - 文集 闭包,就是能够读取其他函数内部变量的函数。Swift 中的闭包与 C 和 OC 中的...

  • swift4 闭包

    swift 闭包 闭包:swift 中 函数是闭包的一种类似于oc的闭包闭包表达式(匿名函数) -- 能够捕获上下...

  • Swift-闭包

    Swift 闭包 函数 ()->() Swift 中的闭包和 Objective-C 中的 block 类似,闭包...

  • swift 闭包(闭包表达式、尾随闭包、逃逸闭包、自动闭包)

    闭包是自含的函数代码块,可以在代码中被传递和使用 闭包和swift的对比 Swift 中闭包与OC的 block ...

  • 100 Days of Swift - Day 06 - 闭包(

    100 Days of Swift - Day 06 - 闭包Closures 6.1 闭包 Swift函数也属于...

  • swift中的闭包

    swift中的闭包 闭包是自包含的函数代码块,可以在代码中被传递和使用。swift中的闭包与C和Objective...

  • Swift闭包和函数

    函数在Swift中只是一种特殊的闭包,闭包在Swift语言中是一等公民,支持闭包嵌套和闭包传递。Swift中的闭包...

  • Swift学习:闭包

    本篇将详细总结介绍Swift闭包的用法;闭包是自包含的函数代码块,可以在代码中被传递和使用。Swift中的闭包与C...

  • Swift (一)--闭包

    @[TOC](Swift (一)--闭包) 1. 闭包简介 什么是闭包 闭包就是能够读取其他函数内部变量的函数,可...

网友评论

      本文标题:swift 函数与闭包

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