ios개발/개념 정리
<스위프트> map, reduce, sort, filter
studying develop
2020. 3. 31. 19:37
- Map: Transform the array contents.
- Reduce: Reduce the values in the collection to a single value.
- Sort: Sorting the arrays.
- Filter: Transform the array contents.
map(_:)
Returns an array containing the results of mapping the given closure over the sequence’s elements.
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]
reduce(_:_:)
Returns the result of combining the elements of the sequence using the given closure.
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
sort()
Sorts the collection in place.
var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort()
print(students)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"