以闭包或函数为参数的函数
let storage = [1, 324, 64564, 125, 789, 91, 77, 12345]//创建测试库
func separate(orignArray: [Int], by filter: (Int) -> Bool) -> (paired: [Int], cantPaired: [Int]) {//分割数组的函数
var paired: [Int] = []
var cantPaired: [Int] = []
for item in orignArray {
if filter(item) {
paired.append(item)
}else {
cantPaired.append(item)
}
}
return (paired: paired, cantPaired: cantPaired)
}
func getOddNum(num: Int) -> Bool {//判断是否为奇数
if num%2 != 0 {
return true
}else {
return false
}
}
func getEvenNum(num: Int) -> Bool {//判断是否为偶数
if num%2 == 0 {
return true
}else {
return false
}
}
print("storage: \(storage)\n---------------------------------------------------")
print("getOdd:\n paired: \(separate(orignArray: storage, by: getOddNum).paired)\n cantPaired: \(separate(orignArray: storage, by: getOddNum).cantPaired)")
print("getEven:\n paired: \(separate(orignArray: storage, by: getEvenNum).paired)\n cantPaired: \(separate(orignArray: storage, by: getEvenNum).cantPaired)")
运行结果如下
storage: [1, 324, 64564, 125, 789, 91, 77, 12345]
---------------------------------------------------
getOdd:
paired: [1, 125, 789, 91, 77, 12345]
cantPaired: [324, 64564]
getEven:
paired: [324, 64564]
cantPaired: [1, 125, 789, 91, 77, 12345]