Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created April 6, 2020 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/4ca37c321fb64fc376b100b2f6b08ef5 to your computer and use it in GitHub Desktop.
Save rayfix/4ca37c321fb64fc376b100b2f6b08ef5 to your computer and use it in GitHub Desktop.
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