Short Answer
Wrap the string in AttributedString(markdown: my_string_here)
:
let string: String = "[Apple Link](http://www.apple.com)"
Text(try! AttributedString(markdown: string))
Extension
extension String {
func toMarkdown() -> AttributedString {
do {
return try AttributedString(markdown: self)
} catch {
print("Error parsing Markdown for string \(self): \(error)")
return AttributedString(self)
}
}
}
Long Answer
SwiftUI Text
has multiple initializers.
For String
:
init<S>(_ content: S) where S : StringProtocol
For AttributedString
:
init(_ attributedContent: AttributedString)
When you declare a static string, Swift is able to guess whether the intent is to use a String
or AttributedString
(Markdown). However, when you use a dynamic string, Swift needs help in figuring out your intent.
As a result, with a dynamic string, you have to explicitly convert your String
into an AttributedString
:
try! AttributedString(markdown: string)