Skip to content

Instantly share code, notes, and snippets.

View CrystDragon's full-sized avatar

Lincoln Wu CrystDragon

View GitHub Profile

Motivation

Swift’s type system supports a number of different ways of taking a function or type and abstracting it. Usually, this is done by adding a generic parameter and an associated set of constraints. Similarly, a function that takes a particular type of argument can be abstracted to any number of those arguments by making it variadic with triple-dot (...) syntax. Today, both of these features are permitted separately: you can define a generic function that takes a variable number of arguments, such as

func debugPrint<T>(_ items: T...) 
  where T: CustomDebugStringConvertible
{   
  for (item: T) in items {
    stdout.write(item.debugDescription)
@DougGregor
DougGregor / macros.md
Last active October 24, 2023 16:42
A possible vision for macros in Swift

A Possible Vision for Macros in Swift

As Swift evolves, it gains new language features and capabilities. There are different categories of features: some fill in gaps, taking existing syntax that is not permitted and giving it a semantics that fit well with the existing language, with features like conditional conformance or allowing existential values for protocols with Self or associated type requirements. Others introduce new capabilities or paradigms to the language, such as the addition of concurrency or comprehensive reflection.

There is another large category of language features that provide syntactic sugar to eliminate common boilerplate, taking something that can be written out in long-form and making it more concise. Such features don't technically add any expressive power to the language, because you can always write the long-form version, but their effect can be transformational if it enables use cases that would otherwise have been unwieldy. The synthesis of Codable conformances, for ex