Skip to content

Instantly share code, notes, and snippets.

@JensAyton
Last active June 9, 2023 10:01
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 JensAyton/586f707722bb0b9715eba5bfb4a10c99 to your computer and use it in GitHub Desktop.
Save JensAyton/586f707722bb0b9715eba5bfb4a10c99 to your computer and use it in GitHub Desktop.
Getting an array of descriptions from a value pack in Swift 5.9 (WWDC 2023 beta)
// Given a value pack in Swift, one would like to be able to accumulate some uniformly-typed property into an array like so:
[repeat String(describing: each element)]
// However, this is not currently supported
// (error: value pack expansion can only appear inside a function argument list or tuple element)
//
// A workaround is to use the tuple conversion capability, with a side-effecting transformation:
var elementDescriptions: [String] = []
func accumulate(_ string: String) {
elementDescriptions.append(string)
}
(repeat accumulate(String(describing: each element)))
// This fills out `elementDescriptions` while producing a tuple of Voids, which can be implicitly discarded.
//
// I don’t like it because it feels like having side effects in a `map`, even though the imperative `repeat` is right there.
// In any case, I believe this is the only workable approach right now.
//
// Also note that this can’t be abstracted out into a function, because it would require same-type constraints:
func accumulate<each T, R>(_ elements: repeat each T) -> [R] where repeat each T == R {}
// error: Same-element requirements are not yet supported
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment