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.

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

-2

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.