나의 발자취

KeyPath란? 본문

프로젝트

KeyPath란?

달모드 2024. 12. 10. 21:21

스위프트를 하면서 심심찮게 \.self 나 \.dismiss를 볼 수 있다. 이는 KeyPath인데, KeyPath는 타입의 특정 속성을 참조하는 방법입니다. 쉽게 말해서 "경로"를 나타내는 것

 

예시는 이렇다.

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

let people = [
    Person(name: "Kim", age: 25),
    Person(name: "Lee", age: 30),
    Person(name: "Park", age: 35)
]

// 1. KeyPath 사용
let names = people.map(\.name)  // ["Kim", "Lee", "Park"]
// 위 코드는 아래와 동일:
// let names = people.map { $0.name }

// 2. KeyPath 변수로 저장
let nameKeyPath = \Person.name
let ageKeyPath = \Person.age

// 3. KeyPath 사용
let firstPerson = people[0]
let name = firstPerson[keyPath: nameKeyPath]  // "Kim"

 

KeyPath의 장점:

  • 코드가 더 간결해짐
  • 속성을 변수처럼 저장하고 전달할 수 있음
  • 컴파일 시점에 타입 안전성 보장
 
 

그래서 ForEach(array, id: \.self)에서 \.self는 "배열의  요소 자체"를 식별자로 사용하겠다는 의미이다.

Comments