본문 바로가기

iOS/STUDY

[iOS] Identifiable 프로토콜

https://developer.apple.com/tutorials/app-dev-training/making-reminders-identifiable#Make-the-Model-Identifiable

 

Apple Developer Documentation

 

developer.apple.com

Apple의 UIKit Tutorial (미리알림 앱)을 보고 공부한 내용을 정리한 글입니다.

 

 

diffable data source는 collection view의 각 항목 ID를 나타내는 identifier list를 저장합니다.

 

이전 강의에서는 미리알림의 title 제목을 identifier로 지정하여 저장했는데

미리알림의 제목을 변경하거나 동일한 제목의 미리 알림(Reminder)이 있다면

그 cell을 나타내는 identifier로 더이상 사용할 수 없게 될 것입니다.

 

그래서 identifier를 지정하기 위해서 Identifiable 프로토콜을 따르도록 합니다.

 

Indetifiable 프로토콜

@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public protocol Identifiable {

    /// A type representing the stable identity of the entity associated with
    /// an instance.
    associatedtype ID : Hashable

    /// The stable identity of the entity associated with this instance.
    var id: Self.ID { get }
}
A class of types whose instances hold the value of an entity with stable identity.
instance가 안정적인 Identity를 가진 Entity의 값을 보유하는 유형의 클래스 입니다.

 

Identity는

 

1. 항상 고유(unique) 함을 보장합니다. (ex. UUID)

2. 환경마다 영구적으로 고유(unique)합니다. (ex. 데이터베이스 recode 키)

3. 프로세스의 lifetime 동안 고유(unique)합니다. (ex. global incrementing integers)

4. object의 lifetime 동안 고유(unique)합니다. (ex. object identifiers)

5. 현재 Collection 내에서 고유(unique)합니다. (ex. Collection index)

 

 

Identifiable은 object의 lifetime 동안에만 unique 하게 유지되도록 보장합니다.

object에 보다 강력한 ID 개념이 있는 경우 사용자가 직접 구현하는 것이 적절하다고 합니다.

 

결론) struct나 class를 정의할 때 ID 값이 필요한 경우 Identifier 프로토콜을 채택합니다!

 

 

+) associatedtype

정의하는 프로토콜이 채택되기 전까지 실제 타입이 명시되지 않는다.

 

 

Reminder 에 Identifiable 을 채택

struct Reminder: Identifiable {
    var id: String = UUID().uuidString
    var title: String
    var dueDate: Date
    var notes: String? = nil
    var isComplete: Bool = false
}

id 프로퍼티만 선언해주면 됩니다.

 

UUID란?

Universally unique identifier, 소프트웨어 구축에 쓰이는 식별자 표준

 

Swift는 Foundation에서 UUID를 제공해줍니다 ㅎㅎ

String 값으로 가져오려면 UUID().uuidString 으로 가져오면 되겠네요.

 

 

 

더 자세한 UUID 참고

https://medium.com/@jang.wangsu/ios-swift-uuid%EB%8A%94-%EC%96%B4%EB%96%A4-%EC%9B%90%EB%A6%AC%EB%A1%9C-%EB%A7%8C%EB%93%A4%EC%96%B4%EC%A7%80%EB%8A%94-%EA%B2%83%EC%9D%BC%EA%B9%8C-22ec9ff4e792

 

[iOS, Swift] UUID는 어떤 원리로 만들어지는 것일까..

갑자기! 문득! 그냥! 별생각 없이!!! iOS? UUID의 생성 알고리즘에 대해 고민이 들어서 검색해 봤어요.

medium.com