고차함수 sort, sorted, reduced

Updated:

🔷 고차함수 sort, sorted

// 고차함수 sort, sorted
var myArray = [1, 3, 2, 5, 9, 7, 6, 8, 10]

// sorted 를 통해 오름차순으로 정렬한 새 콜렉션을 반환함
var filteredArray = myArray.sorted()
print("myArray: \(myArray)") // myArray: [1, 3, 2, 5, 9, 7, 6, 8, 10]
print("filteredArray: \(filteredArray)") // filteredArray: [1, 2, 3, 5, 6, 7, 8, 9, 10]

// collection 내의 데이터 들을 번갈아 가면서 돌기
// 반환 값이 true 가 나올때 해당하는 녀석을 넣게 됩니다. 그래서 내림차순으로 정렬됨
var descendingArray = myArray.sorted(by: {(someValue: Int, otherValue: Int) -> Bool in
	return someValue > otherValue
})
print("descendingArray: \(descendingArray)") // descendingArray: [10, 9, 8, 7, 6, 5, 3, 2, 1]

// closure 부분 축약 버전
var myDescendingArray = myArray.sorted(by: {
	return $0 > $1
})
print("myDescendingArray : \(myDescendingArray)") // myDescendingArray : [10, 9, 8, 7, 6, 5, 3, 2, 1]


// >, < 을 통해 보다 간편하게 정렬이 가능하다
var shortenDescendingArray = myArray.sorted(by: >)
print("shortenDecendingArray : \(shortenDescendingArray)")

var shortenAsendingArray = myArray.sorted(by: <)
print("shortenAsendingArray : \(shortenAsendingArray)")

// sort() 메소드를 통해 해당 배열 자체를 정렬한다
myArray.sort()
myArray.sort(by: >)
myArray.sorted(by: {
	return $0 < $1
})
myArray.sorted(by: { (someValue: Int, otherValue: Int) -> Bool in
	return someValue > otherValue
})

🔷 고차함수 reduced

struct Friend {
	var name: String
	var age: Int
}

let myFriends = [
	Friend(name: "Jacob", age: 30),
	Friend(name: "Emma", age: 40),
	Friend(name: "Paul", age: 50)
]

// reduce 를 통해 collection 으로 하나 값 계산이 가능합니다
// $0 : 결과 / $1 : 각 아이템
// 예) 결과 + 친구 나이 더하기를 collection 갯수 만큼 진행
// 0 이 처음 result 에 대한 초기값
let totalAge_00 = myFriends.reduce(0) { (result: Int, nextItem: Friend) -> Int in
	return result + nextItem.age
}

// 아래와 같이 축약 표현이 가능합니다
let totalAge_01 = myFriends.reduce(0, { (result: Int, nextItem: Friend) in
	return result + nextItem.age
})

let totalAge_02 = myFriends.reduce(0, { result, nextItem in
	return result + nextItem.age
})

let totalAge_03 = myFriends.reduce(0, { result, nextItem in
	result + nextItem.age
})

let totalAge_04 = myFriends.reduce(0, { $0 + $1.age})

let totalAge_05 = myFriends.reduce(0) { $0 + $1.age}

print(totalAge_00) // 120
print(totalAge_01) // 120
print(totalAge_02) // 120
print(totalAge_03) // 120
print(totalAge_04) // 120
print(totalAge_05) // 120


Reference

Swift Tip of the day - 스위프트 기초 문법 - https://spangle-wedelia-2dc.notion.site/Swift-Tip-of-the-day-c428bfd990674bcfa2a4973e5d08c4eb

꼼꼼한 재은 씨의 스위프트 문법편 - https://book.jacobko.info/#/book/1186710233

Categories:

Updated:

Leave a comment