Swift--闭包

2021-12-28  本文已影响0人  冰棍儿好烫嘴

闭包表达式

func sum(_ v1:Int,_ v2:Int) -> Int {v1+v2}
var fn = {
    (v1:Int,v2:Int) -> Int in
    return v1+v2
}
fn(10,20)
写法:
{
    (参数列表) -> 返回值类型  in
    函数体代码
}
 {
    (v1:Int,v2:Int) -> Int in
    return v1+v2
}(10,20)
类似于匿名函数,定义完直接调用

闭包表达式的简写

func exec(v1:Int,v2:Int,fn:(Int,Int) -> Int) {
    print(fn(v1,v2))
}

exec(v1: 10, v2: 20, fn: {
    (v1:Int,v2:Int) -> Int in
    return v1+v2
})

exec(v1: 10, v2: 20, fn: {
    v1,v2 in return v1+v2
})

exec(v1: 10, v2: 20, fn: {
    v1,v2 in v1+v2
})

exec(v1: 10, v2: 20, fn: {$0 + $1})

exec(v1: 10, v2: 20, fn: +)

尾随闭包

func exec(v1:Int,v2:Int,fn:(Int,Int) -> Int) {
    print(fn(v1,v2))
}

exec(v1: 10, v2: 20){
    $0 + $1
}
func exec(fn:(Int,Int) -> Int) {
    print(fn(1,2))
}

exec(fn: { $0 + $1 })
exec(){ $0 + $1 }
exec{ $0 + $1 }

示例 - 数组的排序

///返回true:i1排在i2前面
///返回false:i1排在i2后面
func cmp(i1:Int,i2:Int) -> Bool {
    //大的排在前面
    return i1>i2
}
var nums = [11,2,18,6,5,68,45]
nums.sort(by: cmp)
nums.sort(by: {
    (i1:Int,i2:Int)->Bool in
    return i1>i2
})
nums.sort(by: { i1,i2 in return i1 > i2})
nums.sort(by: { i1,i2 in i1 > i2})
nums.sort(by: { $0 > $1})
nums.sort(by: >)
nums.sort(){ $0 > $1 }
nums.sort{ $0 > $1 }

闭包

typealias Fn = (Int) -> Int

func getFn() -> Fn {
    var num = 0
    func plus(_ i:Int) -> Int {
        num += i
        return num
    }
    return plus
}
var fn = getFn()
print(fn(1))//1
print(fn(2))//3
print(fn(3))//6
print(fn(4))//10
class Closure {
    var num = 0
    func plus(_ i:Int) -> Int {
        num += i
        return num
    }
}
var cs1 = Closure()
var cs2 = Closure()
cs1.plus(1)//1
cs2.plus(2)//2
cs1.plus(3)//4
cs2.plus(4)//6
cs1.plus(5)//9
cs2.plus(6)//12
typealias Fn = (Int) -> (Int,Int)

func getFn() -> (Fn,Fn) {
    var num1 = 0
    var num2 = 0
    
    func plus(_ i:Int) -> (Int,Int){
        num1 += i
        num2 += i << 1
        return (num1,num2)
    }
    func minus(_ i:Int) -> (Int,Int){
        num1 -= i
        num2 -= i << 1
        return (num1,num2)
    }
    return (plus,minus)
}

let (p,m) = getFn()
p(5)//(5,10)
m(4)//(1,2)
p(3)//(4,8)
m(2)//(2,4)

知识点补充--Swift中的位运算符

var a: UInt8 = 0b00001000
var b: UInt8 = 0b01001010
(1)取反运算符“~”: ~a = 0b11110111
(2)与运算符“&”: a&b = 0b00001000
(3)或运算符“|”: a|b = 0b01001010
(4)异或运算符“^”: a^b = 0b01000010
(5)左移运算符“<<”: a<<1 = 0b00010000
(6)右移运算符“>>”: a>>1 = 0b00000100
上一篇下一篇

猜你喜欢

热点阅读