An extension to Text that allows you to join an array of Text into a single Text with optional separators.
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
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