https://developer.apple.com/tutorials/app-dev-training/making-reminders-identifiable
오늘도 Apple 의 튜토리얼을 따라하다가 extension 에서 where 을 추가해서 사용하는 것을 보고 궁금해서 글을 적어봅니다.
extension Array where Element == Reminder {
func indexOfReminder(with id: Reminder.ID) -> Self.Index {
guard let index = firstIndex(where: { $0.id == id }) else {
fatalError()
}
return index
}
}
Reminder 배열에서 id로 reminder를 찾아서 반환하는 함수를 만든다길래 indexOfReminder 함수만 만들줄 알았는데
Array Collection(struct) 를 extension 해서 함수를 만들더라구요.
적혀있는 코멘트
You can use the generic where clause to conditionally extend a generic type.
Generic where 절을 사용해서 조건부로 확장할 수 있다.
이해가 가지않아서 따로 더 찾아보았습니다.
Generic where 절을 사용하는 것은 extension에 새로운 제약사항을 부여할 수 있는 방법이라고 합니다.
그렇다면 여기서 Array의 Element 가 Reminder 형식일 때 이 함수를 실행할 수 있는 것이겠네요.
Array를 확장해서 사용한 이유는 Reminder 일 때만 실행할 수 있도록 제약을 주기 위해서라고 이해가 갑니다.
+) firstIndex() 함수
Returns the first index in which an element of the collection satisfies the given predicate.
func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Int?
Array.Index 는 Int 의 type alias 입니다. (Self.Index 는 Int)
순간 index 라길래 String 의 index 를 생각했는데 배열의 index 는 Int!
참조
https://0urtrees.tistory.com/141
'iOS > STUDY' 카테고리의 다른 글
[iOS] Diffable Data Source (CollectionView, TableView) (0) | 2022.03.10 |
---|---|
[iOS] Identifiable 프로토콜 (0) | 2022.03.10 |
[iOS] Format the Date and Time (0) | 2022.03.07 |
[iOS] UICollectionViewDiffableDataSource (0) | 2022.03.05 |
[iOS] UICollectionViewLayout (0) | 2022.03.04 |