-
(Swift) sorted()iOS💖 2024. 9. 11. 17:19
- 배열의 Comparable protocol* 요소들을 sorting하는 메소드
- Comparable protocol :
비교연산자 (<. <=, >= and >) 로 비교 가능한 요소
- Comparable protocol :
- default order : ascending order ( < )
예시1)
// ascending let dateString: String = ["2022-03-22", "2022-03-02", "2022-03-03"] let sortedDateString = dateString.sorted() // default: < print(sortedDateString) // ["2022-03-02", "2022-03-03", "2022-03-22"] // descending let descendingDateString = dateString.sorted(by: >) print(descendingDateString) // ["2022-03-22", "2022-03-03", "2022-03-02"]예시2)
struct Chat { let name: String let date: String } extension Chat { static let list: [Chat] = [ Chat(name: "Ablin", date: "2024-01-01"), Chat(name: "Abigail", date: "2024-01-02"), Chat(name: "Sam", date: "2024-01-03"), ] } var chatList: [Chat] = Chat.list chatList = chatList.sorted(by: { chat1, chat2 in return chat1.date > chat2.date // 조건문 descending order } // 결과 // [Chat(name: "Sam", date: "2024-01-03"), Chat(name: "Abigail", date: "2024-01-02"), Chat(name: "Ablin", date: "2024-01-01")]https://developer.apple.com/documentation/swift/array/sorted()
sorted() | Apple Developer Documentation
Returns the elements of the sequence, sorted.
developer.apple.com
'iOS💖' 카테고리의 다른 글
(Swift) visibleItemsInvalidationHandler (0) 2024.09.25 (Swift) UISearchController로 Search Bar 구현하기 (0) 2024.09.12 (Swift) DateFormatter (1) 2024.09.11 (Swift) NumberFormatter 정수 / 소수 자릿수 정하기 (2) 2024.09.11 (Swift) CollectionView Estimate Size 코드 설정 (0) 2024.09.10 - 배열의 Comparable protocol* 요소들을 sorting하는 메소드