1

Is there a way to get the Markdown string from an AttributedString? I have the following code:

let text = "**Hello** World!"
let attString = AttributedString(text)

Now I want to get back the Markdown string. I did see that AttributedString includes a description call that attempts to address the problem, but it adds a set of brackets to the result:

print(attString.description)

Result:

**Hello** World! {
}

I thought there might be a better way of doing this.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
reza23
  • 3,079
  • 2
  • 27
  • 42
  • AttributedString conforms to Codable so the output you see from `description` is json. You could use a `JSONEncoder.encode()` together with `String(data:encoding:)` for a quick solution otherwise [this question](https://stackoverflow.com/questions/75544793/encode-attributedstring-with-custom-attributes-to-json) might be of interest. – Joakim Danielson May 14 '23 at 19:51

2 Answers2

1

Markdown is a way to construct AttributedString as a convenience. It is not the internal format of AttributedString. Most things that an AttributedString can represent cannot even be represented in Markdown. In the most basic example, AttributedString can define the exact font for a region. There is no way to express that in Markdown. At the extreme, AttributedString can represent any attributes, including custom ones defined in your code, not just ones defined by Foundation.

But in your case, I believe the confusion is more basic. The "Markdown" in question is just the string. If you want that, then that's fetched with:

String(attString.characters)

(Somewhat surprisingly there is no .string property. This is because it's more expensive to construct than it looks.)

What you've built here isn't an AttributedString defined by Markdown. That would require calling try AttributedString(markdown: text). It's just a string that happens to have asterisks in it. If you really did create a formatted AttributedString with Markdown, and needed to get the Markdown back, you would need to track that yourself in a wrapper type that contained an AttributedString and the Markdown String.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
-1

As suggested by @paulo-mattos here is the solution:

let text = "**Hello** World!"
let attString = AttributedString(text)
let data = try JSONEncoder().encode(attString)
if let stringValue = String( data: data, encoding:.utf8 ){
    print( stringValue)
}
reza23
  • 3,079
  • 2
  • 27
  • 42