How to use compactMap to transform an array in Swift

1 Answer

0 votes
func multiply (n: Int) -> Int {
    return n * 2
}

var arr = [4, 8, 1, 0, 2]

print(arr)

arr = arr.compactMap(multiply)

print(arr)



 
/*
run:
 
[4, 8, 1, 0, 2]
[8, 16, 2, 0, 4]
 
*/

 



answered Nov 9, 2020 by avibootz

Related questions

1 answer 66 views
3 answers 224 views
1 answer 77 views
77 views asked Mar 5, 2025 by avibootz
1 answer 167 views
167 views asked Nov 8, 2020 by avibootz
1 answer 184 views
184 views asked Sep 19, 2020 by avibootz
...