struct Person {
var age: Int
var name: String
}
func getAges(people: [Person]) -> [Int] {
return people.compactMap { $0.age }
}
let r1 = 0...5
let r2 = [0,1,2,3,4,5]
print(r1,r2)
print("map的用法:", r1.map{$0*2} , r2.map{$0*2})
print("filter的用法:",r1.filter{$0>2})
print("reduce的用法:",r1.reduce(50,{$0 + $1}))
let numbersCompound = [[1,2,3],[4,5,6]];
let flatRes = numbersCompound.flatMap{ $0.map{ $0} }
print("flatMap的用法:",flatRes)
let possibleNumbers = ["1", "2", "three", "///4///", "5"]
let compactMapRes: [Int] = possibleNumbers.compactMap { str in Int(str) }
print("compactMap的用法:",compactMapRes)
print( "compactMap的高级用法:",getAges(people: [Person(age: 10, name: "100"),Person(age: 100, name: "100"),Person(age: 1000, name: "100")]))
let rigou = [1, 2, 3, nil, nil, 4, 5] //神奇的空值过滤
let rigouNewArr = rigou.compactMap { $0 }
print(rigouNewArr)
let numbers = [1, 2, 3, 4]
let mapped = numbers.map {Array(repeating: $0, count: $0) }
let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
print(mapped)
print(flatMapped)