Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

sanichdaniel의 iOS 개발 블로그

Identifiable 본문

swift

Identifiable

sanich8355 2020. 10. 7. 01:12

요약

Identifiable, ObjectIdentifier, Equality, Identity 개념들을 묶어서 정리해보았다

Identifiable

A class of types whose instances hold the value of an entity with stable identity.
public protocol Identifiable {

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

    /// The stable identity of the entity associated with `self`.
    var id: Self.ID { get }
}

ObjectIdentifier

A unique identifier for a class instance or metatype.

class 인스턴스메타타입을 유니크하게 구별하는 인스턴스를 생성한다. 

class IntegerRef {
	let value: Int

	init(_ value: Int) {
		self.value = value
    }
}

let x = IntegerRef(10)
let y = x

print(ObjectIdentifier(x) == ObjectIdentifier(y))

// Prints "true"

print(x === y)

// Prints "true"

let z = IntegerRef(10)

print(ObjectIdentifier(x) == ObjectIdentifier(z))

// Prints "false"
print(x === z)
// Prints "false"

 

ObjectIdentifier은 내부적으로 객체의 메모리 주소 래퍼이다.

 

reference 타입은 Identiable 프로토콜을 채택하면 기본으로 ObjectIdentifer을 가지게 된다.

 

ObjectIdentifier은 메타타입에게 Hashable 능력을 줄 수 있다.
메타타입으로 Set, Dictionary을 만들때 유용하다

 

Equality vs Identity

== : Equtable에 정의한대로 값이 같은지

===: 같은 인스턴스를 참조하는지(같은 메모리 위치를 가리키는지)

 

출처

nshipster.com/identifiable/

developer.apple.com/documentation/swift/equatable

'swift' 카테고리의 다른 글

Pure functions in swift  (0) 2020.10.14
일급 시민 함수 - swift  (0) 2020.10.14
Hashable  (0) 2020.10.07
KeyPath  (0) 2020.10.03
Generic where cause  (0) 2020.10.01