SE-0356 introduces the concept of snippets, which are designed to fill a small but important documentation gap for projects: sample code bigger than simple API documentation, but smaller than an example project, designed to show off one specific thing in your project.
On the surface that seems simple enough, and you can certainly imagine providing snippets that demonstrate a single API, or a solution for a particular problem, but there are three things that make snippets particularly interesting:
The special markup comes in two forms: you can use //!
comments to create a short description for each snippet, and you can use // MARK: Hide
and // MARK: Show
to create invisible blocks of code, for when you need to do some work that isn’t specifically relevant to whatever your snippet is trying to demonstrate.
So, we could create a snippet like this:
//! Demonstrates how to use conditional conformance
//! to add protocols to a data type if it matches
//! some constraint.
struct Queue<Element> {
private var array = [Element]()
// MARK: Hide
mutating func append(_ element: Element) {
array.append(element)
}
mutating func dequeue() -> Element? {
guard array.count > 0 else { return nil }
return array.remove(at: 0)
}
// MARK: Show
}
extension Queue: Encodable where Element: Encodable { }
extension Queue: Decodable where Element: Decodable { }
extension Queue: Equatable where Element: Equatable { }
extension Queue: Hashable where Element: Hashable { }
let queue1 = Queue<Int>()
let queue2 = Queue<Int>()
print(queue1 == queue2)
That uses // MARK: Hide
and // MARK: Show
to hide some implementation details, letting readers focus on the part that matters.
As for the command-line support, we can now run three new command variations:
Each snippet you create can access all the code you’ve created in the rest of your package, meaning that they are just fantastic ways of providing hands-on example code for various parts of your projects.
SPONSORED You know StoreKit, but you don’t want to do StoreKit. RevenueCat makes it easy to deploy, manage, and analyze in-app subscriptions on iOS and Android so you can focus on building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Download all Swift 5.7 changes as a playground Link to Swift 5.7 changes
Link copied to your pasteboard.