How to take values from custom multiple attributes in AttributedString - like ^[Text](arg1: '', arg2: '')

According to the WWDC 21 Session https://developer.apple.com/videos/play/wwdc2021/10109/

It shows how can we describe custom attributes in markdown as followings:

This text contains ^[an attribute](rainbow: 'extreme').

This text contains ^[two attributes](rainbow: 'extreme', otherValue: 42).

This text contains ^[an attribute with 2 properties](someStuff: {key: true, key2: false}).

So, the first one, I can guess how to create, and last one could archive with describing Value type as a Struct.

However, I don't know how to handle the second case.

CodableAttributedStringKey and MarkdownDecodableAttributedStringKey allow us to override decoding function. but that decoding function's Decoder can only accept to access to the value which comes from first attribute. Like rainbow's container.

So how can we take the value in otherValue as 42?

Answered by Frameworks Engineer in 720493022

In the second string you have in your example, rainbow and otherValue are two separate attributes. So, the rainbow attribute's MarkdownDecodableAttributedStringKey.decodeMarkdown(from:) will indeed only be called for the rainbow attribute value ("extreme"). To decode otherValue, you'll need to create a second attribute to represent otherValue. If you provide a scope that contains both attributes, foundation will call the decodeMarkdown(from:) function on each attribute present and each attribute type will only decode it's own value (so the rainbow attribute will decode the 'extreme' value and the otherValue attribute will decode the 42 value)

Could this help ? https://mackuba.eu/notes/wwdc21/whats-new-in-foundation/

Accepted Answer

In the second string you have in your example, rainbow and otherValue are two separate attributes. So, the rainbow attribute's MarkdownDecodableAttributedStringKey.decodeMarkdown(from:) will indeed only be called for the rainbow attribute value ("extreme"). To decode otherValue, you'll need to create a second attribute to represent otherValue. If you provide a scope that contains both attributes, foundation will call the decodeMarkdown(from:) function on each attribute present and each attribute type will only decode it's own value (so the rainbow attribute will decode the 'extreme' value and the otherValue attribute will decode the 42 value)

How to take values from custom multiple attributes in AttributedString - like ^[Text](arg1: '', arg2: '')
 
 
Q