Skip to content

Instantly share code, notes, and snippets.

@ryanlintott
Last active July 10, 2023 15:13
Show Gist options
  • Save ryanlintott/66b58972d8d05be83c9379bf35efeabb to your computer and use it in GitHub Desktop.
Save ryanlintott/66b58972d8d05be83c9379bf35efeabb to your computer and use it in GitHub Desktop.
An extension to Text that allows you to join an array of Text into a single Text with optional separators.
extension Collection where Element == Text {
func joined() -> Text {
reduce(into: Text("")) {
$0 = $0 + $1
}
}
func joined(separator: String) -> Text {
joined(separator: Text(separator))
}
func joined(separator: Text) -> Text {
guard let first else {
return Text("")
}
let joined = self
.dropFirst()
.reduce(into: Text("")) {
$0 = $0 + separator + $1
}
return first + joined
}
}
struct Example: View {
var body: some View {
[
Text(Image(systemName: "cloud"))
.accessibilityLabel( "Streamable.")
.foregroundColor(.blue),
Text("\(Date().formatted(date: .abbreviated, time: .omitted))")
].joined(separator: " ")
.foregroundColor(.red)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment