
resultBuilderでSwiftUIのTextを連結する
以前この記事でSwiftUIのTextを連結する方法を書いたのですが、resultBuilderを使えばもっと使い勝手が良くなるのではと考えました。
なおresultBuilderについてはお馴染みSwiftLee先生の記事が参考になります!
本題に入る前に、なぜView BuilderではなくresultBuilderなのかについて。
実はiOS18から追加されたGroup.initを使えばできるんじゃないと思って試したのですが、この方法だとTextにキャストできないという問題があって実現できませんでした。
extension Text {
static func joined(@ViewBuilder _ content: () -> some View) -> some View {
Group(subviews: content()) { subviews in
subviews.reduce(Text("")) { joined, subview in
// ⚠️Cast from 'SubviewsCollection.Element' (aka 'Subview') to unrelated type 'Text' always fails
guard let text = subview as? Text else { return joined }
return joined + text
}
}
}
}というわけで、Textに限定した独自のresultBuilderを実装しました。
extension Text {
@resultBuilder
struct TextBuilder {
static func buildBlock(_ components: [Text]...) -> [Text] { components.flatMap { $0 } }
static func buildExpression(_ expression: Text) -> [Text] { [expression] }
static func buildExpression(_ expression: [Text]) -> [Text] { expression }
static func buildOptional(_ components: [Text]?) -> [Text] { components ?? [] }
static func buildEither(first components: [Text]) -> [Text] { components }
static func buildEither(second components: [Text]) -> [Text] { components }
static func buildFinalResult(_ components: [Text]) -> some View {
Group {
if components.isEmpty {
EmptyView()
} else {
components.reduce(Text("")) { $0 + $1 }
}
}
}
}
static func joined(@TextBuilder _ content: () -> some View) -> some View {
content()
}
}
// Usage
func description(for event: EKEvent) -> some View {
Text.joined {
if event.hasNotes, let note = event.notes {
Text(Image(systemName: "note.text"))
Text(note)
}
if let location = event.location {
Text(Image(systemName: "mappin.and.ellipse"))
Text(location)
}
}
.lineLimit(1)
.font(.caption2)
.foregroundStyle(.secondary)
}別にTextを連結せずとも元のStringをjoined()で連結すればいいのでは?と思うかもしれませんが、以前の記事にあるようなテキスト内に画像を入れたい場合はTextでの連結が有用です。またresultBuilderの利点として、if-elseなどの条件文を使い連結を制御できます。