---
title: KeyPathを使って再帰的な構造体にアクセスしやすくする
tags: 
author: [Ockey](https://www.docswell.com/user/Ockey)
site: [Docswell](https://www.docswell.com/)
thumbnail: https://bcdn.docswell.com/page/YJ6LLGNMEV.jpg?width=480
description: KeyPathを使って再帰的な構造体にアクセスしやすくする by Ockey
published: August 29, 25
canonical: https://www.docswell.com/s/Ockey/K37YJM-pixiv-App-Night-KeyPath
---
# Page. 1

![Page Image](https://bcdn.docswell.com/page/YJ6LLGNMEV.jpg)

KeyPathを使って再帰的な構造体にアクセスしやすくする
2025/07/10 pixiv App Night / ockey


# Page. 2

![Page Image](https://bcdn.docswell.com/page/GJ511V5Q74.jpg)

• 2025年4月新卒入社
• PalcyのiOSアプリエンジニア
• 好きなSwift
Ockey
- enum
- guard
- KeyPath


# Page. 3

![Page Image](https://bcdn.docswell.com/page/LE311DNZ75.jpg)

KeyPath、使っていますか？


# Page. 4

![Page Image](https://bcdn.docswell.com/page/8EDXXPW4JG.jpg)

import SwiftUI
struct NumbersList: View {
let numbers = [0, 1, 2]
var body: some View {
List(numbers, id: \.self) { number in
Text(&quot;\(number)&quot;)
}
}
}


# Page. 5

![Page Image](https://bcdn.docswell.com/page/V7PPPN9V78.jpg)

import SwiftUI
これ
struct NumbersList: View {
let numbers = [0, 1, 2]
var body: some View {
List(numbers, id: \.self) { number in
Text(&quot;\(number)&quot;)
}
}
}


# Page. 6

![Page Image](https://bcdn.docswell.com/page/2JV22KMRJQ.jpg)

KeyPathを使うと、
どのプロパティにアクセスするかを
型安全に制御できる


# Page. 7

![Page Image](https://bcdn.docswell.com/page/5EGRRQG6JL.jpg)

KeyPathのおかげで解決できた課題に
ついてお話しします


# Page. 8

![Page Image](https://bcdn.docswell.com/page/4JQVVKX27P.jpg)

目次
1. KeyPathとは
2. 再帰的な構造体
3. 再帰的な構造体で直面した課題
4. KeyPathを使った方針
5. KeyPathを動的に生成する
6. まとめ


# Page. 9

![Page Image](https://bcdn.docswell.com/page/K74MMP6PJ1.jpg)

KeyPathとは


# Page. 10

![Page Image](https://bcdn.docswell.com/page/LJ1889VXEG.jpg)

KeyPathとは
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/expressions/#Key-Path-Expression


# Page. 11

![Page Image](https://bcdn.docswell.com/page/GJWZZQLKJ2.jpg)

KeyPathとは
1. 簡単な使い方
2. 型が同じプロパティ
3. Array
4. Optional
5. Dictionary


# Page. 12

![Page Image](https://bcdn.docswell.com/page/4EZ11WMN73.jpg)

KeyPathとは｜簡単な使い方
struct Person {
var name: String
var emailAddress: String
var age: Int
}
let me = Person(
name: &quot;ockey&quot;,
emailAddress: &quot;ockey@mail.com&quot;,
age: 10
)
2つの型を設定する
• Root: プロパティの持ち主
• Value: プロパティ
let toName: KeyPath&lt;Person, String&gt; = \Person.name


# Page. 13

![Page Image](https://bcdn.docswell.com/page/Y76LLGN9JV.jpg)

KeyPathとは｜簡単な使い方
struct Person {
var name: String
var emailAddress: String
var age: Int
}
let me = Person(
name: &quot;ockey&quot;,
emailAddress: &quot;ockey@mail.com&quot;,
age: 10
)
let toName: KeyPath&lt;Person, String&gt; = \.name
Rootは型推論が効くので省略可


# Page. 14

![Page Image](https://bcdn.docswell.com/page/G7511V5DE4.jpg)

KeyPathとは｜簡単な使い方
struct Person {
var name: String
var emailAddress: String
var age: Int
}
let me = Person(
name: &quot;ockey&quot;,
emailAddress: &quot;ockey@mail.com&quot;,
age: 10
)
let toName: KeyPath&lt;Person, String&gt; = \.name
me[keyPath: toName]
// &quot;ockey&quot;
[keyPath:]サブスクリプトに渡すと
プロパティにアクセスできる


# Page. 15

![Page Image](https://bcdn.docswell.com/page/9J2113GM7R.jpg)

KeyPathとは｜型が同じプロパティ
struct Person {
var name: String
var emailAddress: String
var age: Int
}
型が同じであれば、別のプロパティにも
アクセスできる
let me = Person(
name: &quot;ockey&quot;,
emailAddress: &quot;ockey@mail.com&quot;,
age: 10
)
var toString: KeyPath&lt;Person, String&gt; = \.name
me[keyPath: toString]
// &quot;ockey&quot;
toString = \.emailAddress
me[keyPath: toString]
// &quot;ockey@mail.com&quot;


# Page. 16

![Page Image](https://bcdn.docswell.com/page/DEYZZ1VP7M.jpg)

KeyPathとは｜Array(1/3)
struct Person {
var name: String
var emailAddresses: [String]
var age: Int
}
Arrayなプロパティも指定できる
let me = Person(
name: &quot;ockey&quot;,
emailAddresses: [&quot;ockey@mail.com&quot;, &quot;ockey@mail.jp&quot;],
age: 10
)
me[keyPath: \.emailAddresses]
// [&quot;ockey@mail.com&quot;, &quot;ockey@mail.jp&quot;]


# Page. 17

![Page Image](https://bcdn.docswell.com/page/VJN332MMJ8.jpg)

KeyPathとは｜Array(2/3)
struct Person {
var name: String
var emailAddresses: [String]
var age: Int
}
Arrayの要素をインデックスで指定できる
let me = Person(
name: &quot;ockey&quot;,
emailAddresses: [&quot;ockey@mail.com&quot;, &quot;ockey@mail.jp&quot;],
age: 10
)
me[keyPath: \.emailAddresses[0]]
// &quot;ockey@mail.com&quot;


# Page. 18

![Page Image](https://bcdn.docswell.com/page/YE9991NWE3.jpg)

KeyPathとは｜Array(3/3)
struct Person {
var name: String
var emailAddresses: [String]
var age: Int
}
要素のプロパティも指定できる
let me = Person(
name: &quot;ockey&quot;,
emailAddresses: [&quot;ockey@mail.com&quot;, &quot;ockey@mail.jp&quot;],
age: 10
)
me[keyPath: \.emailAddresses[0]].count
// 14


# Page. 19

![Page Image](https://bcdn.docswell.com/page/GE8994KR7D.jpg)

KeyPathとは｜Optional(1/3)
struct Person {
var name: String
var middleName: String?
var age: Int
}
Optional型のプロパティを指定できる
let me = Person(
name: &quot;ockey&quot;,
age: 10
)
let toMiddleName: KeyPath&lt;Person, String?&gt; = \.middleName
me[keyPath: toMiddleName]
// nil


# Page. 20

![Page Image](https://bcdn.docswell.com/page/LELWW6Z2JR.jpg)

KeyPathとは｜Optional(2/3)
struct Person {
var name: String
var middleName: String?
var age: Int
}
Optional Chainingできる
ValueはOptional型になる
let me = Person(
name: &quot;ockey&quot;,
middleName: &quot;Swift&quot;,
age: 10
)
let toMiddleNameCount: KeyPath&lt;Person, Int?&gt; = \.middleName?.count
me[keyPath: toMiddleNameCount]
// 5


# Page. 21

![Page Image](https://bcdn.docswell.com/page/4JM995V9EW.jpg)

KeyPathとは｜Optional(3/3)
struct Person {
var name: String
var middleName: String?
var age: Int
}
RootをOptional型にすると、
ValueもOptional型になる
let who: Person? = Person(
name: &quot;ockey&quot;,
age: 10
)
let toName: KeyPath&lt;Person?, String?&gt; = \.?.name
who[keyPath: toName]
// &quot;ockey&quot;


# Page. 22

![Page Image](https://bcdn.docswell.com/page/PJRGG329E9.jpg)

KeyPathとは｜Dictionary(1/2)
struct Book: Identifiable {
let id: UUID
let name: String
}
struct Person {
var name: String
var books: [UUID: Book]
}
Keyを指定してDictionaryのValueに
アクセスできる
ValueはOptionalになる
let id = UUID()
let book = Book(id: id, name: &quot;Swift Masters Guide&quot;)
let me = Person(name: &quot;ockey&quot;, books: [id: book])
let toBook: KeyPath&lt;Person, Book?&gt; = \.books[id]
me[keyPath: toBook]
// Book


# Page. 23

![Page Image](https://bcdn.docswell.com/page/PEXXX4D3EX.jpg)

KeyPathとは｜Dictionary(2/2)
struct Book: Identifiable {
let id: UUID
let name: String
}
Optional ChainingでValueの
プロパティにアクセスできる
struct Person {
var name: String
var books: [UUID: Book]
}
let id = UUID()
let book = Book(id: id, name: &quot;Swift Masters Guide&quot;)
let me = Person(name: &quot;ockey&quot;, books: [id: book])
let toBookName: KeyPath&lt;Person, String?&gt; = \.books[id]?.name
me[keyPath: toBookName]
// &quot;Swift Masters Guide&quot;


# Page. 24

![Page Image](https://bcdn.docswell.com/page/3EKWWZXNED.jpg)

再帰的な構造体


# Page. 25

![Page Image](https://bcdn.docswell.com/page/L7311D5ZJ5.jpg)

再帰的な構造体
Swiftで書かれたコードを解析するツールを開発中
• 型とメンバの構造をツリー形式で表示する
• シンボル同士の依存関係を可視化する


# Page. 26

![Page Image](https://bcdn.docswell.com/page/87DXXPD4EG.jpg)

再帰的な構造体
ツリー形式で表示するために、階層構造を維持したまま宣言を抽出したい
@Observable
class MainViewModel {
var count: Int
func increment() {
count += 1
}
}
init(count: Int) {
self.count = count
}
• MainViewModel
- count
- increment ()
- init()


# Page. 27

![Page Image](https://bcdn.docswell.com/page/VJPPPNXVJ8.jpg)

再帰的な構造体
ツリーのViewで扱いやすいように、構造体を使って階層構造を表したい
Swiftでは[Self]型のプロパティを宣言できる
Self型はコンパイルエラーになる
struct Type {
var children: [Self]
}
// Value type &#039;Type&#039; cannot have a stored
property that recursively contains it
var child: Self


# Page. 28

![Page Image](https://bcdn.docswell.com/page/2EV22KLREQ.jpg)

再帰的な構造体
[Self]型のプロパティを持つ構造体を、この発表では再帰的な構造体と呼ぶ
struct Type {
var children: [Self]
}


# Page. 29

![Page Image](https://bcdn.docswell.com/page/57GRRQX6EL.jpg)

再帰的な構造体
型やメンバの階層構造を維持したまま抽出するために、宣言1つを
表す再帰的なDeclaration構造体を宣言する
struct Declaration: Identifiable {
let id: String
let name: String
// 宣言に関するその他の情報
}
var properties: [Self]
var methods: [Self]
var initializers: [Self]


# Page. 30

![Page Image](https://bcdn.docswell.com/page/4EQVVK82JP.jpg)

再帰的な構造体
Declaration構造体にメンバを格納していくことで、階層構造を維持できる
@Observable
class MainViewModel {
var count: Int
func increment() {
count += 1
}
}
init(count: Int) {
self.count = count
}
• MainViewModel
• Declaration
- count
- Declaration
- increment ()
- Declaration
- init()
- Declaration


# Page. 31

![Page Image](https://bcdn.docswell.com/page/KJ4MMP2PE1.jpg)

再帰的な構造体で直面した課題


# Page. 32

![Page Image](https://bcdn.docswell.com/page/LE1889MX7G.jpg)

再帰的な構造体で直面した課題
コンパイラは各シンボルに一意な識別子(USR)を割り当てる
Symbol
Symbol
Symbol
USR
USR
USR


# Page. 33

![Page Image](https://bcdn.docswell.com/page/GEWZZQ3KE2.jpg)

再帰的な構造体で直面した課題
Declaration構造体のidは、コンパイラが各シンボルに割り当てた
一意な識別子(USR)を使う
Symbol
Symbol
Symbol
USR
struct Declaration: Identifiable {
let id: String
let name: String
// 宣言に関するその他の情報
USR
USR
}
var properties: [Self]
var methods: [Self]
var initializers: [Self]


# Page. 34

![Page Image](https://bcdn.docswell.com/page/47Z11WVNJ3.jpg)

再帰的な構造体で直面した課題
シンボルの依存関係は、参照する側とされる側のUSRの組として
取得できる
Symbol
Symbol
Symbol
USR
USR
USR


# Page. 35

![Page Image](https://bcdn.docswell.com/page/YJ6LLG59EV.jpg)

再帰的な構造体で直面した課題
ツールでシンボルを選択すると、依存関係がある他のシンボルを
リスト形式で表示したい
Symbol
Symbol
Symbol
USR
USR
USR
Declaration
Declaration
Declaration


# Page. 36

![Page Image](https://bcdn.docswell.com/page/GJ511VYD74.jpg)

再帰的な構造体で直面した課題
依存関係があるシンボルに対応するDeclarationインスタンスに、
USRを元にしてアクセスできるようにする必要がある
Symbol
Symbol
Symbol
USR
USR
USR
Declaration
Declaration
Declaration


# Page. 37

![Page Image](https://bcdn.docswell.com/page/9E2113YMJR.jpg)

再帰的な構造体で直面した課題
ネストが深いと、USRがわかっても簡単にはアクセスできない
func functionA() {
func functionB() {}
func functionC() {
func functionD() {
func functionE() {
func functionG() {}
func functionH() {}
func functionI() {}
}
func functionF() {
func functionJ() {}
}
}
}
}
• functionA
- functionB
- functionC
• functionD
- functionE
• functionG
• functionH
• functionI
- functionF
• functionJ


# Page. 38

![Page Image](https://bcdn.docswell.com/page/D7YZZ1GPJM.jpg)

再帰的な構造体で直面した課題
USRが一致する要素を見つけるまで毎回探索していると効率が悪い
• functionA
- functionB
- functionC
• functionD
- functionE
• functionG
• functionH
• functionI
- functionF
• functionJ
• functionA
- functionB
- functionC
• functionD
- functionE
• functionG
• functionH
• functionI
- functionF
• functionJ


# Page. 39

![Page Image](https://bcdn.docswell.com/page/VEN332GME8.jpg)

再帰的な構造体で直面した課題
USRをKeyとするDictionaryを生成するとO(1)で見つけられる
struct Declaration: Identifiable {
let id: String
let name: String
// 宣言に関するその他の情報
var properties: [Self] = []
var methods: [Self] = []
var initializers: [Self] = []
}
var table: [String: Declaration] = [:]
let id = &quot;sampleID&quot;
let function = Declaration(id: id, name: &quot;sampleFunction&quot;)
table[id] = function
if let function = table[id] {}


# Page. 40

![Page Image](https://bcdn.docswell.com/page/Y79991WW73.jpg)

再帰的な構造体で直面した課題
孫、子、親をそれぞれValueに格納すると孫が3つ存在してしまう
let grandchildID = &quot;grandchildID&quot;
let grandchild = Declaration(
id: grandchildID,
name: &quot;grandchildFunction&quot;
)
table[grandchildID] = grandchild
let childID = &quot;childID&quot;
let child = Declaration(
id: childID,
name: &quot;childFunction&quot;,
methods: [grandchild]
)
table[childID] = child
• grandchild
• child
- grandchild
let parentID = &quot;parentID&quot;
let parent = Declaration(
id: parentID,
name: &quot;parentFunction&quot;,
methods: [child]
)
table[parentID] = parent
• parent
- child
• grandchild


# Page. 41

![Page Image](https://bcdn.docswell.com/page/G78994NRJD.jpg)

再帰的な構造体で直面した課題
今後の拡張性を考慮するとSingle Source of Truthに反する実装は避けたい
let grandchildID = &quot;grandchildID&quot;
let grandchild = Declaration(
id: grandchildID,
name: &quot;grandchildFunction&quot;
)
table[grandchildID] = grandchild
let childID = &quot;childID&quot;
let child = Declaration(
id: childID,
name: &quot;childFunction&quot;,
methods: [grandchild]
)
table[childID] = child
• grandchild
• child
- grandchild
let parentID = &quot;parentID&quot;
let parent = Declaration(
id: parentID,
name: &quot;parentFunction&quot;,
methods: [child]
)
table[parentID] = parent
• parent
- child
• grandchild


# Page. 42

![Page Image](https://bcdn.docswell.com/page/L7LWW6P2ER.jpg)

Dictionaryで効率よくアクセスしたい
かつ
Single Source of Truthも維持したい


# Page. 43

![Page Image](https://bcdn.docswell.com/page/4EM995497W.jpg)

DictionaryのValueに
アクセスしたい要素そのものではなく
要素までアクセスする方法を格納したい


# Page. 44

![Page Image](https://bcdn.docswell.com/page/PERGG3W979.jpg)

KeyPathがある！


# Page. 45

![Page Image](https://bcdn.docswell.com/page/P7XXX4P37X.jpg)

KeyPathを使った方針


# Page. 46

![Page Image](https://bcdn.docswell.com/page/37KWWZDN7D.jpg)

KeyPathを使った方針
• 最も階層が浅いインスタンス1つをRootとする
• RootをSingle Source of Truthとする
• DictionaryのValueには、Rootからその要素までのKeyPathを格納する


# Page. 47

![Page Image](https://bcdn.docswell.com/page/LJ311DRZE5.jpg)

KeyPathを使った方針
struct Declaration: Identifiable {
let id: String
let name: String
// その他のプロパティ
型やメンバの宣言1つに対応する
Declaration構造体
}
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
}
struct Directory: Identifiable {
var id: String { fullPath }
let fullPath: String
var subdirectories: [Self]
var files: [File]
}
struct RootDirectory {
var directory: Directory
var keyPathTable: [String: KeyPath&lt;Directory, Declaration&gt;]
}


# Page. 48

![Page Image](https://bcdn.docswell.com/page/8JDXXPY47G.jpg)

KeyPathを使った方針
struct Declaration: Identifiable {
let id: String
let name: String
// その他のプロパティ
Swiftファイル1つに対応するFile構造体
}
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
}
ファイル内の宣言を持つ
struct Directory: Identifiable {
var id: String { fullPath }
let fullPath: String
var subdirectories: [Self]
var files: [File]
}
struct RootDirectory {
var directory: Directory
var keyPathTable: [String: KeyPath&lt;Directory, Declaration&gt;]
}


# Page. 49

![Page Image](https://bcdn.docswell.com/page/VEPPPN6VE8.jpg)

KeyPathを使った方針
struct Declaration: Identifiable {
let id: String
let name: String
// その他のプロパティ
ディレクトリ1つに対応するDirectory構造体
}
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
}
サブディレクトリとファイルを持つ
struct Directory: Identifiable {
var id: String { fullPath }
let fullPath: String
var subdirectories: [Self]
var files: [File]
}
struct RootDirectory {
var directory: Directory
var keyPathTable: [String: KeyPath&lt;Directory, Declaration&gt;]
}


# Page. 50

![Page Image](https://bcdn.docswell.com/page/27V22K3R7Q.jpg)

KeyPathを使った方針
struct Declaration: Identifiable {
let id: String
let name: String
// その他のプロパティ
}
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
}
struct Directory: Identifiable {
var id: String { fullPath }
let fullPath: String
var subdirectories: [Self]
var files: [File]
}
最も階層が浅いディレクトリに対応する
RootDirectory構造体
DirectoryからDeclarationまでのKeyPathを
格納するDictionaryを持つ
struct RootDirectory {
var directory: Directory
var keyPathTable: [String: KeyPath&lt;Directory, Declaration&gt;]
}


# Page. 51

![Page Image](https://bcdn.docswell.com/page/5JGRRQ367L.jpg)

KeyPathを使った方針
struct Declaration: Identifiable {
let id: String
let name: String
// その他のプロパティ
}
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
}
struct Directory: Identifiable {
var id: String { fullPath }
let fullPath: String
var subdirectories: [Self]
var files: [File]
}
最終的に、RootDirectoryインスタンスを1つ
生成してSingle Source of Truthとする
ディレクトリ、ファイル、宣言の構造を維持
したまま抽出する
SwiftSyntaxで抽出する流れは省略
struct RootDirectory {
var directory: Directory
var keyPathTable: [String: KeyPath&lt;Directory, Declaration&gt;]
}


# Page. 52

![Page Image](https://bcdn.docswell.com/page/47QVVK52EP.jpg)

KeyPathを使った方針
USRを受け取ってDeclarationインスタンスを返すメソッドを実装することで
KeyPathのDictionaryをモジュール内に隠蔽できる
public struct RootDirectory {
var directory: Directory
var keyPathTable: [String: KeyPath&lt;Directory, Declaration&gt;]
}
public func getDeclaration(_ usr: String) -&gt; Declaration? {
guard let toDeclaration = keyPathTable[usr] else {
return nil
}
return directory[keyPath: toDeclaration]
}


# Page. 53

![Page Image](https://bcdn.docswell.com/page/KE4MMP9P71.jpg)

各DeclarationまでのKeyPathを
動的に生成する必要がある


# Page. 54

![Page Image](https://bcdn.docswell.com/page/L71889KXJG.jpg)

KeyPathを動的に生成する


# Page. 55

![Page Image](https://bcdn.docswell.com/page/G7WZZQDK72.jpg)

KeyPathを動的に生成する
説明を簡単にするために、Fileから各DeclarationまでのKeyPathを
生成する流れのみを対象とする
public struct Declaration: Identifiable {
public let id: String
let name: String
var properties: [Self]
// その他のプロパティ
}
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
}


# Page. 56

![Page Image](https://bcdn.docswell.com/page/4JZ11WGNE3.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = KeyPath&lt;File, Declaration&gt;
typealias KeyPathTable = [String: ToDeclaration]
public struct Declaration: Identifiable {
public let id: String
let name: String
var properties: [Self]
// その他のプロパティ
}
Dictionaryを生成するメソッドを
Declarationに実装する
func generateKeyPath(fromRoot keyPath: ToDeclaration) -&gt; KeyPathTable {
var table: KeyPathTable = [id: keyPath]
for (index, declaration) in properties.enumerated() {
let toChild: ToDeclaration = keyPath.appending(path: \.properties[index])
table.merge(
declaration.generateKeyPath(fromRoot: toChild),
uniquingKeysWith: { current, new in current }
)
}
return table
}


# Page. 57

![Page Image](https://bcdn.docswell.com/page/YE6LLGY97V.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = KeyPath&lt;File, Declaration&gt;
typealias KeyPathTable = [String: ToDeclaration]
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
}
Dictionaryを生成するメソッドを
Fileにも実装する
func generateKeyPath() -&gt; KeyPathTable {
var table: KeyPathTable = [:]
for (index, declaration) in declarations.enumerated() {
table.merge(
declaration.generateKeyPath(fromRoot: \.declarations[index]),
uniquingKeysWith: { current, new in current }
)
}
return table
}


# Page. 58

![Page Image](https://bcdn.docswell.com/page/GE511VGDJ4.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = KeyPath&lt;File, Declaration&gt;
typealias KeyPathTable = [String: ToDeclaration]
struct File: Identifiable {
var id: String { fullPath }
let fullPath: String
var declarations: [Declaration]
インデックスを含めたKeyPathを生成
してDeclarationのメソッドを呼び出す
インデックスが必要なので親から渡す
}
func generateKeyPath() -&gt; KeyPathTable {
var table: KeyPathTable = [:]
for (index, declaration) in declarations.enumerated() {
table.merge(
declaration.generateKeyPath(fromRoot: \.declarations[index]),
uniquingKeysWith: { current, new in current }
)
}
return table
}


# Page. 59

![Page Image](https://bcdn.docswell.com/page/972113DMER.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = KeyPath&lt;File, Declaration&gt;
typealias KeyPathTable = [String: ToDeclaration]
public struct Declaration: Identifiable {
public let id: String
let name: String
var properties: [Self]
// その他のプロパティ
}
Fileから受け取ったKeyPathで
Dictionaryを初期化する
func generateKeyPath(fromRoot keyPath: ToDeclaration) -&gt; KeyPathTable {
var table: KeyPathTable = [id: keyPath]
for (index, declaration) in properties.enumerated() {
let toChild: ToDeclaration = keyPath.appending(path: \.properties[index])
table.merge(
declaration.generateKeyPath(fromRoot: toChild),
uniquingKeysWith: { current, new in current }
)
}
return table
}


# Page. 60

![Page Image](https://bcdn.docswell.com/page/DJYZZ12PEM.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = KeyPath&lt;File, Declaration&gt;
typealias KeyPathTable = [String: ToDeclaration]
public struct Declaration: Identifiable {
public let id: String
let name: String
var properties: [Self]
// その他のプロパティ
}
ネストしたpropertiesについて同じ
メソッドを再帰的に呼び出す
func generateKeyPath(fromRoot keyPath: ToDeclaration) -&gt; KeyPathTable {
var table: KeyPathTable = [id: keyPath]
for (index, declaration) in properties.enumerated() {
let toChild: ToDeclaration = keyPath.appending(path: \.properties[index])
table.merge(
declaration.generateKeyPath(fromRoot: toChild),
uniquingKeysWith: { current, new in current }
)
}
return table
}


# Page. 61

![Page Image](https://bcdn.docswell.com/page/V7N3328M78.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = KeyPath&lt;File, Declaration&gt;
typealias KeyPathTable = [String: ToDeclaration]
public struct Declaration: Identifiable {
public let id: String
let name: String
var properties: [Self]
// その他のプロパティ
}
インデックスを含むKeyPathを
継ぎ足して渡す
func generateKeyPath(fromRoot keyPath: ToDeclaration) -&gt; KeyPathTable {
var table: KeyPathTable = [id: keyPath]
for (index, declaration) in properties.enumerated() {
let toChild: ToDeclaration = keyPath.appending(path: \.properties[index])
table.merge(
declaration.generateKeyPath(fromRoot: toChild),
uniquingKeysWith: { current, new in current }
)
}
return table
}


# Page. 62

![Page Image](https://bcdn.docswell.com/page/YJ9991KWJ3.jpg)

KeyPathを動的に生成する
File
File
File.declarations[0]
KeyPathは継ぎ足せる
Declaration
Declaration.properties[0]
File.declarations[0]
Declaration.properties[0]
+
var toDeclaration: KeyPath&lt;File, Declaration&gt; = \.declarations[0]
let toProperty: KeyPath&lt;Declaration, Declaration&gt; = \.properties[0]
toDeclaration.appending(path: toProperty)
// File.declarations[0].properties[0]


# Page. 63

![Page Image](https://bcdn.docswell.com/page/GJ8994RRED.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = KeyPath&lt;File, Declaration&gt;
typealias KeyPathTable = [String: ToDeclaration]
public struct Declaration: Identifiable {
public let id: String
let name: String
var properties: [Self]
// その他のプロパティ
}
返ってきたDictionaryを
mergeして返す
func generateKeyPath(fromRoot keyPath: ToDeclaration) -&gt; KeyPathTable {
var table: KeyPathTable = [id: keyPath]
for (index, declaration) in properties.enumerated() {
let toChild: ToDeclaration = keyPath.appending(path: \.properties[index])
table.merge(
declaration.generateKeyPath(fromRoot: toChild),
uniquingKeysWith: { current, new in current }
)
}
return table
}


# Page. 64

![Page Image](https://bcdn.docswell.com/page/LJLWW6K27R.jpg)

KeyPathを動的に生成する
let childID = &quot;childID&quot;
let child = Declaration(id: childID, name: &quot;childProperty&quot;)
let parentID = &quot;parentID&quot;
let parent = Declaration(
id: parentID,
name: &quot;parent&quot;,
properties: [child]
)
USRに一致するKeyPathをDictionaryから取り出して
Fileの[keyPath:]サブスクリプトに渡すことで、
Declarationにアクセスできる
var file = File(fullPath: &quot;/path/to/file&quot;, declarations: [parent])
let table = file.generateKeyPath()
if let toChild = table[childID] {
file[keyPath: toChild].name
// &quot;childProperty&quot;
}


# Page. 65

![Page Image](https://bcdn.docswell.com/page/47M99529JW.jpg)

KeyPathを動的に生成する
typealias ToDeclaration = WritableKeyPath&lt;File, Declaration&gt;
let childID = &quot;childID&quot;
let child = Declaration(id: childID, name: &quot;childProperty&quot;)
let parentID = &quot;parentID&quot;
let parent = Declaration(
id: parentID,
name: &quot;parent&quot;,
properties: [child]
)
KeyPathをWritableKeyPathに変えると、
Declarationの更新もできるようになる
var file = File(fullPath: &quot;/path/to/file&quot;, declarations: [parent])
let table = file.generateKeyPath()
if let toChild = table[childID] {
file[keyPath: toChild].properties.append(
Declaration(id: &quot;newChildID&quot;, name: &quot;newChildProperty&quot;)
)
}


# Page. 66

![Page Image](https://bcdn.docswell.com/page/P7RGG3M9J9.jpg)

まとめ


# Page. 67

![Page Image](https://bcdn.docswell.com/page/PJXXX4V3JX.jpg)

まとめ
• KeyPathはArrayやOptional、Dictionaryも扱える
• DictionaryでKeyPathを保持することで再帰的な構造体にアクセス
しやすくできる
• KeyPathは継ぎ足せる
Swiftの強力な機能を活用していきましょう💪


