AttributedString Attribute Scopes
UIKit and AppKit attribute scopes have many attributes with matching names but different value types. Attributes with types defined in UIKit such as
UIColor
,UIFont
etc. are available on platforms that can import UIKit and attributes with types defined in AppKit such asNSColor
,NSFont
etc. are available on macOS. AttributeScopes.UIKitAttributes type contains the full list of UIKit attributes and AttributeScopes.AppKitAttributes contains the full list of AppKit attributes.Foundation can infer the right type of the attribute to use when we assign the value. The following code will assign
UIColor.blue
as foreground color when UIKit is imported andNSColor.blue
when AppKit is imported.[…]
Note, that when SwiftUI is imported SwiftUI attributes take priority and the resulting attribute value will be
Color.blue
that is defined in the SwiftUI framework.[…]
We can even define our own attributes and attribute scopes. This can be useful if we are building a framework or a package or just want to extend
AttributedString
functionality in our app.
See also: NSAttributedStringBuilder (via Kaya Thomas).
Previously:
- AttributedString’s Codable Format
- Heterogeneous Swift Dictionary With Strong Types
- Surprises When Using Markdown in SwiftUI
- Swift Foundation Formatter Improvements