본문 바로가기
Apple/Apple_Swift

KeyPath란?

by LeviiOS 2024. 8. 8.
반응형

1. KeyPath

 

KeyPath란?

 

KeyPath는 Swift에서 타입 안전하게 프로퍼티에 접근할 수 있는 기능입니다. 객체의 프로퍼티 경로를 나타내며, 이를 통해 해당 프로퍼티의 값을 읽거나 쓸 수 있습니다.

 

KeyPath 사용 예시

 

먼저, KeyPath를 사용하는 간단한 예시를 살펴보겠습니다.

struct Person {
    var name: String
    var age: Int
}

let person = Person(name: "John", age: 30)

// KeyPath 생성
let nameKeyPath = \Person.name
let ageKeyPath = \Person.age

// KeyPath를 사용하여 값 읽기
let name = person[keyPath: nameKeyPath]
let age = person[keyPath: ageKeyPath]

print("Name: \(name), Age: \(age)")

KeyPath를 사용한 값 수정

 

KeyPath를 사용하여 값을 수정할 수도 있습니다. 이를 위해서는 WritableKeyPath를 사용합니다.

var person = Person(name: "John", age: 30)

// WritableKeyPath를 사용하여 값 수정
person[keyPath: nameKeyPath] = "Jane"
person[keyPath: ageKeyPath] = 25

print("Updated Name: \(person.name), Updated Age: \(person.age)")

KeyPath의 응용

 

KeyPath는 고차 함수와 함께 사용할 때 특히 유용합니다. 예를 들어, 배열의 특정 프로퍼티 값을 추출하거나, 필터링할 때 사용할 수 있습니다.

let people = [
    Person(name: "Alice", age: 28),
    Person(name: "Bob", age: 34),
    Person(name: "Charlie", age: 22)
]

// KeyPath를 사용하여 이름 추출
let names = people.map(\.name)
print("Names: \(names)")

// KeyPath를 사용하여 특정 나이 이상의 사람 필터링
let adults = people.filter { $0[keyPath: ageKeyPath] > 30 }
print("Adults: \(adults.map(\.name))")
반응형