map
.map操作,对数组中的元素添加相同类型值,返回相同类型
let numbers = [1,2,3,4,5,6,7,8,9]
let result1 = numbers.map({
$0 + 2
})
//result1 = [3, 4, 5, 6, 7, 8, 9, 10, 11]
.map操作,对数组中的元素添加不同类型值,返回不同类型
let numbers = [1,2,3,4,5,6,7,8,9]
let result2 = numbers.map({
"NO." + "\($0)"
})
//result2 = ["NO.1", "NO.2", "NO.3", "NO.4", "NO.5", "NO.6", "NO.7", "NO.8", "NO.9"]
.map操作,对二维数组中的元素添加相同类型值,返回相同类型
let numbers2 = [[1 ,2 ,3] ,[4, 5, 6]]
let result3 = numbers2.map({
$0.map({
$0 + 1
})
})
//result3 = [[2, 3, 4], [5, 6, 7]]
.map操作 ,对二维数组中元素拼接不同类型值,返回不同类型
let numbers2 = [[1 ,2 ,3] ,[4, 5, 6]]
let result4 = numbers2.map({
$0.map({
"NO." + "\($0)"
})
})
//result4 = [["NO.1", "NO.2", "NO.3"], ["NO.4", "NO.5", "NO.6"]]
flatMap
.flatMap操作,对一维数组中的元素添加相同类型值,返回相同类型
let numbers = [1,2,3,4,5,6,7,8,9]
let result1 = numbers.flatMap({
$0 + 2
})
//result1 = [3, 4, 5, 6, 7, 8, 9, 10, 11]
.flatMap操作 ,对一维数组中元素拼接不同类型值
let numbers = [1,2,3,4,5,6,7,8,9]
let result2 = numbers.flatMap({
"NO." + "\($0)"
})
//result2 = ["N", "O", ".", "1", "N", "O", ".", "2", "N", "O", ".", "3", "N", "O", ".", "4", "N", "O", ".", "5", "N", "O", ".", "6", "N", "O", ".", "7", "N", "O", ".", "8", "N", "O", ".", "9"]
.flatMap操作,对二维数组中的元素添加相同类型值
let numbers2 = [[1 ,2 ,3] ,[4, 5, 6]]
let result3 = numbers2.flatMap({
$0.map({
$0 + 1
})
})
//result3 = [2, 3, 4, 5, 6, 7]
.flatMap操作 ,对二维数组中元素拼接不同类型值,返回不同类型
let numbers2 = [[1 ,2 ,3] ,[4, 5, 6]]
let result4 = numbers2.flatMap({
$0.map({
"NO." + "\($0)"
})
})
//result4 = ["NO.1", "NO.2", "NO.3", "NO.4", "NO.5", "NO.6"]