2022.10.03.
TIL / Swift
let numbers = [1, 2, 3]
// 파라미터, 리턴 생략
let newNumbers = numbers.map {
"숫자: \($0)"
}
print(newNumbers) // ["숫자: 1", "숫자: 2", "숫자: 3"]
let array = ["Red", "Black", "Yellow", "Blue"]
let newArray = array.filter { str in
return str.contains("B")
}
print(newArray) // ["Black", "Blue"]
let oneToTen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 0(초깃값)에 반환값이 누적됨
let total = oneToTen.reduce(0) { prev, next in
return prev + next
}
let stringTotal = oneToTen.reduce("0") { result, item in
return result + String(item)
}
print(total) // 55
print(stringTotal) // "012345678910"
let arrayWithNil = ["A", nil, "B", nil, "C"]
// 옵셔널 요소를 제거하고 새로운 배열을 반환함
let result = arrayWithNil.compactMap { $0 }
print(result) // ["A", "B", "C"]
let nestedArray = [[1, 2, 3,], [4, 5, 6]]
let newNestedArray = nestedArray.flatMap{ $0 }
print(newNestedArray) // [1, 2, 3, 4, 5, 6]