KeyPath

KeyPath

  • ๋ฌธ์ž์—ด ๋ฐฉ์‹์œผ๋กœ ์†์„ฑ์— ๊ฐ„ํŽธํ•˜๊ฒŒ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ ์‚ฌ์šฉํ•œ๋‹ค.

    • ๊ฐ„์ ‘์ ์œผ๋กœ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ

  • Person.name์˜ ๊ฐ’์ด ๋ฐ”๋€Œ๋Š” ์ˆœ๊ฐ„์„ ์•Œ๊ณ  ์‹ถ์„ ๋•Œ!

    • ์†์„ฑ๊ฐ์‹œ์ž๋กœ ํ•˜์ง€ ์•Š๋Š” ์ด์œ 

      • ๊ฐ์ฒด ๋‚ด๋ถ€๊ฐ€ ์•„๋‹Œ, ๊ฐ์ฒด์˜ ์™ธ๋ถ€์—์„œ๋งŒ ๊ด€์ฐฐํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์กด์žฌํ•œ๋‹ค.

    • \Person.name โ†’ ๊ฒฝ๋กœ๋ฅผ ๋งŒ๋“ค๊ณ , ์ธ์Šคํ„ด์Šค ์†์„ฑ์— ์ ‘๊ทผํ•˜๋Š” ๊ธฐ์ˆ ์ด๋‹ค.

Selector

  • ๋ฉ”์„œ๋“œ์˜ ์ฃผ์†Œ๋ฅผ ํ†ตํ•ด ๋ฉ”์„œ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ธฐ ์œ„ํ•œ ๊ธฐ์ˆ 

    • #selector(Person.walk) โ†’ ๋ฉ”์„œ๋“œ๊ฐ€ ๊ตฌํ˜„๋œ ์ฃผ์†Œ๋ฅผ ๊ฐ„์ ‘์ ์œผ๋กœ ๋ฝ‘์•„๋‚ผ ์ˆ˜ ์žˆ๋‹ค.


KeyPath์˜ ์‹œ์ž‘

์–ด๋–ป๊ฒŒ ๋งŒ๋“ค์–ด์ง€๊ฒŒ ๋˜์—ˆ์„๊นŒ?

  • ๊ฐ„์ ‘์ ์œผ๋กœ ์†์„ฑ์„ ์ ‘๊ทผํ•˜๊ณ  ์‹ถ๋‹ค.

    • ํŠน๋ณ„ํ•œ ๋ฌธ์ž์—ด์„ ๋งŒ๋“ค์–ด๋†“๊ณ , ํ•ด๋‹น ์†์„ฑ์— ์ ‘๊ทผํ•˜๊ณ  ์‹ถ์–ด!

    • ์†์„ฑ์— ์กฐ๊ธˆ ๋” ์‰ฝ๊ฒŒ ์ ‘๊ทผํ•˜๊ณ  ์‹ถ์–ด! (์„œ๋ธŒ์Šคํฌ๋ฆฝํŠธ์ฒ˜๋Ÿผ)

์ฝ”๋“œ

class School {
    var name: String
    **var affiliate: SmallSchool**
    
    init(name: String, affiliate: SmallSchool) {
        self.name = name
        self.affiliate = affiliate
    }
}

class SmallSchool {
    **var classMember: Person**
    init(classMember: Person) {
        self.classMember = classMember
    }
}

class Person {
    **var name: String**
    init(name: String) {
        self.name = name
    }
}

// ์ง์ ‘ ์ ‘๊ทผ
let person1 = Person(name: "ํ™๊ธธ๋™")
let smallSchool1 = SmallSchool(classMember: person1)
let school1 = School(name: "์Šˆํผ๊ณ ", affiliate: smallSchool1)

let gildong = school1.affilate.classMember.name

// Swift5์—์„œ์˜ ๊ฐ„์ ‘ ์ ‘๊ทผ
let namePath = \School.affiliate.classMember.name // keyPath ๊ฒฝ๋กœ ์ง€์ •
school1[keyPath: namePath] // ๋”•์…”๋„ˆ๋ฆฌ ๋ฐฉ์‹(์„œ๋ธŒ์Šคํฌ๋ฆฝํŠธ)๋กœ ์ ‘๊ทผ ๊ฐ€๋Šฅ
  • KeyPath = ๊ฒฝ๋กœ

  • ๋Œ€๊ด„ํ˜ธ๋ฅผ ์“ฐ๋ฉด, ๊ฐ„์ ‘์ ์œผ๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.


๊ฒฝ๋กœ ์ถ”๊ฐ€

let namePath = \School.affiliate.classMember     // ๋ฏธ๋ฆฌ ๊ฒฝ๋กœ๋ฅผ ์ง€์ • (**keyPath**)
let newNamePath = namePath.appending(path: \.name)
school1[keyPath: newNamePath]      // appending ๋ฉ”์„œ๋“œ๋กœ ๊ฒฝ๋กœ๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค.

Last updated