AttributedString in Foundation

Updated
Jun 20, 2022 3:16 PM
Created
Oct 1, 2021 6:05 AM
Tags
Swift
Attributes
image

Creating custom attributes

enum RainbowAttribute: CodableAttributedStringKey, MarkdownDecodableAttributedStringKey {
  enum Value: String, Codable, Hashable {
    case plain
    case fun
    case extreme
  }
  
  static var name: String = "rainbow"
}

extension AttributeScopes {
  struct CaffeAppAttributes: AttributeScope {
    let rainbow: RainbowAttribute
  }
  
  var caffeApp: CaffeAppAttributes.Type { CaffeAppAttributes.self }
}

extension AttributeDynamicLookup {
  subscript<T: AttributedStringKey>(dynamicMember keyPath: KeyPath<AttributeScopes.CaffeAppAttributes, T>) -> T {
    self[T.self]
  }
}

^[John](rainbow: 'fun')

AttributedString parses custom attributed text as a JSON5, then using first argument label, matches custom created AttributedStringKey and invokes decoding with Decoder

If CodableAttributedStringKey.Value is compatible with Codable, don’t need to implementations of decoding. It would be automatically invoked and Value should be instantiated.

image

In case of described parameter as (arg1, arg2, arg3)

might need to implement AttributeScopeCodableConfiguration