diff --git a/assets/snippets/Coding.swift b/assets/snippets/Coding.swift new file mode 100644 index 000000000..2fc5c6bfb --- /dev/null +++ b/assets/snippets/Coding.swift @@ -0,0 +1,14 @@ +// Create types that automatically encode to JSON. + +import Foundation + +struct ScientificName: Codable { + var genus: String + var species: String + var subspecies: String? +} + +let momiji = ScientificName(genus: "Acer", species: "palmatum") +let jsonData = try JSONEncoder().encode(momiji) + +// {"genus":"Acer","species":"palmatum"} diff --git a/assets/snippets/IfLet.swift b/assets/snippets/IfLet.swift new file mode 100644 index 000000000..8159088a4 --- /dev/null +++ b/assets/snippets/IfLet.swift @@ -0,0 +1,16 @@ +// Easily reason about data that may or may not be present. + +struct ScientificName { + var genus: String + var species: String + var subspecies: String? + + var description: String { + var text = "\(genus) \(species)" + if let subspecies { + // subspecies is guaranteed to be non-nil here. + text += "subsp. \(subspecies)" + } + return text + } +} \ No newline at end of file diff --git a/assets/snippets/MapReduce.swift b/assets/snippets/MapReduce.swift new file mode 100644 index 000000000..d9f4827ee --- /dev/null +++ b/assets/snippets/MapReduce.swift @@ -0,0 +1,12 @@ +// Use functional programming techniques. + +import Foundation + +func squareWave(phase: Float, overtones: UInt) -> Float { + return (0...overtones) + .map { + let harmonic = Float($0 * 2 + 1) + return sinf(phase * harmonic) / harmonic + } + .reduce(0, +) +} \ No newline at end of file diff --git a/assets/snippets/MultilineString.swift b/assets/snippets/MultilineString.swift new file mode 100644 index 000000000..b7f396e83 --- /dev/null +++ b/assets/snippets/MultilineString.swift @@ -0,0 +1,18 @@ +// Multiline strings with string interpolation. + +let hello = "Hello, world!" +let multilineString = """ + @@@ + @@ @@@@ + @@ @@@ @@@@@ + @@@@@@@@@ @@@@@ + @@@@@@@@@@ @@@@@@ + @@@@@@@@@@ @@@@@@ + @@@@@@@@@@@@@@@@@ + @ @@@@@@@@@@@@@@@ + @@@@@@ @@@@@@@@@@@@@ + @@@@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@@@ @ + \(hello) +"""