swift学习

Swift5.1 - Array的高级用法

2019-09-25  本文已影响0人  HChase
var arr = [1, 2, 3, 4]

// [2, 4, 6, 8]
var arr1 = arr.map{ $0 * 2 }

// [2, 4]
var arr2 = arr.filter { $0 % 2 == 0}

// 10
var arr3 = arr.reduce(0) { $0 + $1 }
var arr = [1, 2, 3, 4]

// [2, 4, 6, 8]
var arr1 = arr.map{ $0 * 2 }

// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
var arr2 = arr.map{ Array.init(repeating: $0, count: $0) }

// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
var arr3 = arr.flatMap { Array.init(repeating: $0, count: $0) }
var arr = ["100", "hello", "-80", "json"]

// [Optional(100), nil, Optional(-80), nil]
var arr1 = arr.map { Int($0) }

// [100, -80]
var arr2 = arr.compactMap { Int($0) }

reduce的应用

使用reduce实现map、filter功能

var arr = [1, 2, 3, 4]

// map功能
// [2, 4, 6, 8]
print( arr.map{ $0 * 2 } )
print( arr.reduce([]) { $0 + [$1 * 2] } )


// filter功能
// [2, 4]
print( arr.filter{ $0 % 2 == 0 } )
print( arr.reduce([]) { $1 % 2 == 0 ? $0 + [$1] : $0 } )
上一篇下一篇

猜你喜欢

热点阅读