6.3 Swift闭包表达式作为回调函数

前端之家收集整理的这篇文章主要介绍了6.3 Swift闭包表达式作为回调函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

/**

闭包表达式作为回调函数

*/

/**

上节课中呢,说了闭包表达式的语法,

将闭包表达式赋给一个常量并不常用,那种调用方式还不如就写成函数的形式

*/

var array = [20,2,3,70,8]

showArray(array: array)

print("-------------->")

bubbleSort(array: &array)

let intCmp = {

(a: Int,b: Int) -> Int in


// 可以修改闭包表达式

// let x = a % 10

// let y = b % 10

if a > b {

return -1

} else if a < b {

return 1

} else {

return 0

}

}

// 这个就是将闭包作为回调函数了,放到函数形式参数的最后一个,这样方便找

//

bubbleSort2(array: &array,cmp: intCmp)

print("----------------->")

showArray(array: array)

// 好处呢,我们可以修改这个 intCmp

let intCmp2 = {

(a: Int,b: Int) -> Int in

// 可以修改闭包表达式

let x = a % 10

let y = b % 10

if x > y {

return -1

} else if x < y {

return 1

} else {

return 0

}

}

// 可以作为实际参数直接放在这里

bubbleSort2(array: &array,cmp: {

(a: Int,0)"> // 可以修改闭包表达式

let x = a % 10

let y = b % 10

if x > y {

return -1

} else if x < y {

return 1

} else {

return 0

}

})

print("----------------->")

showArray(array: array)



func showArray(array: [Int]) -> Void {

for x in array {

print("\(x)")

}

}

// 写个冒泡排序, 函数

func bubbleSort(array:inout [Int]) -> Void {

let cnt = array.count

for (i,value) in array.enumerated()

{

if i > 0

{

for (j,value2) in array.enumerated()

{

// print("j=====\(j)")

// print("====\(cnt - i)")

if j < cnt - i

{

if array[j] > array[j+1]

{

let t = array[j]

array[j] = array[j+1]

array[j+1] = t;

}

}

}

}

}

// 不允许用C方法

// for var i = 1; i < cnt; i++

// {

//

// for var j = 0; j < cnt-i; j++

// {

//

// if array[j] > array[j+1]

// {

//

// let t = array[j]

// array[j] = array[j + 1]

// array[j + 1] = t

// }

// }

// }

}

// 写个冒泡排序, 用闭包表达式作为回调

func bubbleSort2(array:inout [Int],cmp:(Int,Int) -> Int) {

let cnt = array.count

for (i,0)"> // print("j=====\(j)")

// print("====\(cnt - i)")

if j < cnt - i

{

if (cmp(array[j],array[j+1]) == -1)

{

let t = array[j]

array[j] = array[j+1]

array[j+1] = t;

}

}

}

}

}

}

原文链接:https://www.f2er.com/swift/322448.html

猜你在找的Swift相关文章