Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Playing around with KeyPaths in Swift
struct Paragraph {
var words: String
}
struct Chapter {
var title: String
var content: [Paragraph]
}
struct Book {
var title: String
var author: String
var preface: Chapter
var chapters: [Chapter]
}
var introduction = Chapter(title: "Introduction",
content: [Paragraph(words: "Millions and billions...")])
var chapter1 = Chapter(title: "The Shores of the Cosmic Ocean",
content: [Paragraph(words: "paragraph 1"),
Paragraph(words: "paragraph 2"),
Paragraph(words: "paragraph 3")])
var chapter2 = Chapter(title: "One Voice in the Cosmic Fugue",
content: [Paragraph(words: "paragraph 1"),
Paragraph(words: "paragraph 2"),
Paragraph(words: "paragraph 3")])
var chapter3 = Chapter(title: "The Harmony of Worlds",
content: [Paragraph(words: "paragraph 1"),
Paragraph(words: "paragraph 2"),
Paragraph(words: "paragraph 3")])
var cosmos = Book(title: "Cosmos",
author: "Carl Sagan",
preface: introduction,
chapters: [chapter1, chapter2, chapter3])
cosmos[keyPath: \Book.author]
cosmos[keyPath: \.author]
cosmos[keyPath: \.preface.title]
cosmos[keyPath: \.chapters[1].title]
let path = \Book.author
cosmos[keyPath: path] = "Ray"
//func prefaceTitle(_ book: Book) -> String {
// book.preface.title
//}
//var prefaceTitle: (Book) -> String = { book in book.preface.title }
dump(cosmos)
let interestingNumbers = ["prime": [2, 3, 5, 7, 11, 13, 17],
"triangular": [1, 3, 6, 10, 15, 21, 28],
"hexagonal": [1, 6, 15, 28, 45, 66, 91]]
interestingNumbers[keyPath: \[String: [Int]].["prime"]!.count]
interestingNumbers[keyPath: \.self["prime"]![0]]
var compond = (a: 1,b: 2)
compond[keyPath: \.self.a] = 100
compond
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.