-
I have a string:
This should be transformed into SwiftUI Text elements:
Is this a fit task for this parsing library? I have tried a little but not been able to find a solution yet. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Yes, this is possible with the parsing library. You can parse directly into SwiftUI's The intermediate type could be as simple as this: enum Result: Equatable {
case text(String)
case strong(String)
} If you wanted to support more tags you would add onto this enum. Then you have to just describe how to parse from the beginning of an input string to generate values in let text = PrefixUpTo("<strong>".utf8)
.orElse(Rest())
.compactMap {
$0.isEmpty
? nil
: Result.text(String(Substring($0)))
} Similarly, to parse let strong = StartsWith("<strong>".utf8)
.take(PrefixUpTo("</strong>".utf8))
.skip(StartsWith("</strong>".utf8))
.compactMap {
$0.isEmpty
? nil
: Result.strong(String(Substring($0)))
} And finally you can parse a bunch of text and strong tags by using the let results = Many(text.orElse(strong)) Using this with your input string makes the following test pass: let input: Substring = """
Some text with <strong>an important part</strong>, then regular text. \
<strong>finally more important stuff</strong> - perhaps more regular stuff.
"""
XCTAssertEqual(
results.parse(input),
[
.text("Some text with "),
.strong("an important part"),
.text(", then regular text. "),
.strong("finally more important stuff"),
.text(" - perhaps more regular stuff."),
]
) I leave it as an exercise for you to write a function that will transform |
Beta Was this translation helpful? Give feedback.
Yes, this is possible with the parsing library. You can parse directly into SwiftUI's
Text
, but it's easier to first parse into an intermediate type that is easier to handle (and equatable so that it's easier to test), and then map the intermediate type intoText
.The intermediate type could be as simple as this:
If you wanted to support more tags you would add onto this enum. Then you have to just describe how to parse from the beginning of an input string to generate values in
Result
. For example, to parse.text
you just need to take everything up until you either reach a<strong>
tag or until you reach the end of the …