dotSwift 2020 - Denis Poifol - Stating the obvious

rbw·2023년 2월 7일
0

TIL

목록 보기
70/97

https://www.youtube.com/watch?v=IkWtN8v7EiU

내용이 짧아 간단히 ~ 자세한 내용은 위 영상 참조바라바라밤


간단히 모델에 Identifiable, Hashable을 하는 장점에 대한 세션으로 느꼈고, 그로 인해 좀 더 장점들을 소개해주는데 아래와 같은 코드가 흥미로웠다.

아래 코드는 작가 값을 키로 사용하는 딕셔너리를 간단하게 만들어버리는 코드이다

struct Book: Identifiable {
    let id: BookID

    var author: String { id.author }
    var edition: String { id.edition }
    var title: String { id.title }
    let chapterList: [String]
}

struct BookID: Hashable {
    let title: String
    let author: String
    let edition: String
}

// 아래와 같은 제약사항을 지키는 Element를 간단히 딕셔너리로 만들어버릴수가있다 !
// 추가로 키패스를 사용해본적이 거의 없는데 이런식의 활용도 가능한게 흥미로워씀
extension Collection where Element: Identifiable, Element.ID == BookID {
    func grouped<T: Hashable>(by keyPath: KeyPath<BookID, T>) -> [T: [Element]] {
        Dictionary(grouping: self) { element -> T in
        element.id[keyPath: keyPath]
        }
    }
}

let books: [Book] = // Some array of books
// 작가의 이름이 key인 딕셔너리가 생성이 된다 !
let dictionaryOfBooks = books.grouped(by: \.author)
let rollingsBooks = dictionaryOfBooks["J. K. Rollings"]

추가로 위치에 관한 모델을 사용하기 쉽게 프로토콜을 만들고 확장을 우리 입맛대로 추가도 가능함 세션 예제 코드는 다음과 같다

struct CustomMapAnnotationModel: Hashable, Identifiable {
    let id: String
    let location: CLLocation
    let icon: MyIconEnum
    let color: UIColor
    ...
}

// location을 가진다면 ok ~
protocol Locatable {
    var location: CLLocation { get }
}

// 우리가 만든 locatable 들이라면 아래 함수를 사용하여 거리별로 정렬이 가능한 함수를 만들었다
extension Swift.Collection where Element: Locatable {
    func sortedByDistance(from location: CLLocation) -> [Element] {
        // 비교를 위해 튜플로 만드는듯 ? 요렇게는 안써본듯,,
        return map { ($0, location.distance(from: $0.location)) }
            .sorted { $0.1 < $1.1 }
            .map { $0.0 }
    }
}

let fiftyClosestElements = locatables
    .sortedByDistance(from: location)
    .prefix(50)

프로토콜과 확장을 요런식으로 활용하여 코드를 작성하면 좀 더 가독성도 괜찮은 코드를 작성할거라고 생각한다.(프로토콜을 많이 사용하고 여러 모델들이 같은 프로토콜을 채택하는 경우가 많다면 더 유용할 듯 !) 개인적으로 좋은 세션이였으~~

profile
hi there 👋

0개의 댓글