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,UIFontetc. are available on platforms that can import UIKit and attributes with types defined in AppKit such asNSColor,NSFontetc. 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.blueas foreground color when UIKit is imported andNSColor.bluewhen AppKit is imported.[…]
Note, that when SwiftUI is imported SwiftUI attributes take priority and the resulting attribute value will be
Color.bluethat 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
AttributedStringfunctionality 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