美文网首页
swift数组函数:map,filter

swift数组函数:map,filter

作者: 怪客半 | 来源:发表于2017-10-13 10:48 被阅读22次

参考

Swift高阶函数:Map,Filter,Reduce

map

不使用map函数来操作数组(同时熟悉闭包的产生过程):

//第一种:不使用map来操作数组
let mapArray = [1,7,4,8,2]

func add1(a: Int) -> String {
    return "\(a)个"
}

func newArr(a: [Int]) -> [String] {
    var new = [String]()
    for b in a {
        new.append("\(b)个")
    }
    return new
}

let mapArray2 = newArr(a: mapArray)

func newArr2(a: [Int],f: ((Int) -> String)) -> [String] {
    var new = [String]()
    for b in a {
        new.append(f(b))
    }
    return new
}

let mapArray3 = newArr2(a: mapArray, f: add1(a:))

let mapArray4 = newArr2(a: mapArray, f: {(b: Int) -> String in return "\(b)个"})
print(mapArray4)

let mapArray5 = newArr2(a: mapArray, f: {b in return "\(b)个"})
print(mapArray5)

let mapArray6 = newArr2(a: mapArray, f: {b in "\(b)个"})
print(mapArray6)

let mapArray7 = newArr2(a: mapArray, f: {"\($0)个"})
print(mapArray7)

使用map函数:
map函数相当于系统提供的"newArr2"函数,我们只需要写闭包部分

//第二种:使用map来操作数组
let mapArray8 = mapArray.map({"\($0)个"})
print(mapArray8)

let map2Array = ["1","5","3","9","8"]
let map2Array2 = map2Array.map({$0 + "个"})
print(map2Array2)

filter

不使用filter函数来操作数组(同时熟悉闭包的产生过程):

//第一种:不使用filter函数来筛选数组
//筛选出大于30的数
let money = [12,54,34,76,11]
//--------
//直接粗暴型
func filterArr(a: [Int]) -> [Int] {
    var newArr = [Int]()
    for b in a {
        if b > 30 {
            newArr.append(b)
        }
    }
    return newArr
}

let money2 = filterArr(a: money)

//-------
//包含函数参数型
func compare(a: Int) -> Bool {
    if a > 30 {
        return true
    }
    else {
        return false
    }
}
func filterArr2(a: [Int], f: ((Int) -> Bool)) -> [Int] {
    var newArr = [Int]()
    for b in a {
        if f(b) {
            newArr.append(b)
        }
    }
    return newArr
}

let money3 = filterArr2(a: money, f: compare(a:))

//--------
//闭包型
let money4 = filterArr2(a: money, f: { (b) -> Bool in return b>30 })
print(money4)

let money5 = filterArr2(a: money, f: { b in return b>30 })
print(money5)

let money6 = filterArr2(a: money, f: { b in b>30 })
print(money6)

let money7 = filterArr2(a: money, f: { $0 > 30 })
print(money7)

使用filter函数:
filter函数相当于系统提供的"filterArr2"函数,我们只需要写闭包部分

//第二种:使用filter函数来筛选数组
let money8 = money.filter({$0 > 30})
print(money8)

let moneyP = [3,2,11,65,7]
let moneyP2 = moneyP.filter({ $0 < 10 })
print(moneyP2)

reduce

对数组进行计算操作

let subArr = [1,2,3,4,5,6]
let sum = subArr.reduce(0, {$0 + $1})
print(sum)
let mul = subArr.reduce(1, {$0 * $1})
print(mul)

相关文章

网友评论

      本文标题:swift数组函数:map,filter

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