객체의 값을 직접 가져오지 않고,
Key
또는KeyPath
를 이용해서 간접적으로 데이터를 가져오거나 수정하는 방법
값에 대한 참조가 아닌 프로퍼티에 대한 참조
→ 객체 내부의 값에 직접적으로 참조하는 것이 아닌 값의 이름(프로퍼티)을 참조
KeyPath 표현식
\type_name.path
KeyPath 종류
----- Read Only -----
AntyKeyPath
: 타입이 지워진 KeyPath
PartialKeyPath
: 부분적으로 타입이 지워진 KeyPath
KeyPath
: 읽기 전용
----- Writable -----
WritableKeyPath
: 읽기·쓰기 전용
ReferenceWritableKeyPath
: 클래스의 인스턴스에 사용 가능 / 변경 가능한 모든 프로퍼티에 대한 읽기·쓰기 access 제공
KeyPath
속성에 대한 읽기 전용 엑세스
루트 유형은 value / reference 체계일 수 있음
WritableKeyPath
ReferenceWritableKeyPath
Source가 Reference type일 때 사용
struct Employee {
let name: String
let role: String
let level: Int
}
var designer = Employee(name: "Song", role: "Designer", level: 10)
let nameKeyPath = Employee.name
let strKeyPath: KeyPath<String, Int> = String.count
let subscriptKeyPath: KeyPath<[Int], Int> = [Int].count
let arrKeyPath: KeyPath<Array<Int>, Int> = .count
let dictKeyPath = Dictionary<String, Int>.values
let secondDomainKeyPath = [String][1]
struct Videogame {
var title: String
var published: String
var rating: Double
}
let games = [
Videogame(title: "Fight", published: "2020", rating: 999),
Videogame(title: "Race", published: "2015", rating: 4.5),
Videogame(title: "Fallout", published: "2019", rating: 4.4),
Videogame(title: "Bubble Gun", published: "2011", rating: 4),
]
for game in games.sorted(keyPath: \Videogame.rationg, by: >) {
print(game.title)
}