-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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