AttributedString
A value type for a string with associated attributes for portions of its text.
Declaration
@dynamicMemberLookup struct AttributedStringOverview
Attributed strings are character strings that have attributes for individual characters or ranges of characters. Attributes provide traits like visual styles for display, accessibility for guided access, and hyperlink data for linking between data sources. Attribute keys provide the name and value type of each attribute. System frameworks like Foundation and SwiftUI define common keys, and you can define your own in custom extensions.
String Attributes
You can apply an attribute to an entire string, or to a range within the string. The string represents each range with consistent attributes as a run.
AttributedString uses subscripts and dynamic member lookup to simplify working with attributes from your call points. In its most verbose form, you set an attribute by creating an AttributeContainer and merging it into an existing attributed string, like this:
var attributedString = AttributedString("This is a string with empty attributes.")
var container = AttributeContainer()
container[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self] = .red
attributedString.mergeAttributes(container, mergePolicy: .keepNew)Using the attributed string’s subscript(_:) method, you can omit the explicit use of an AttributeContainer and just set the attribute by its type:
attributedString[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self] = .yellowBecause an AttributedString supports dynamic member lookup — as described under Attributes in The Swift Programming Language — you can access its subscripts with dot syntax instead. When combined with properties like foregroundColor that return the attribute key type, this final form offers a natural way to set an attribute that applies to an entire string:
attributedString.foregroundColor = .greenThis example works because AppKit defines an AttributeScope, AttributeScopes.AppKitAttributes, in which the property foregroundColor returns the type AttributeScopes.AppKitAttributes.ForegroundColorAttribute. Because AppKit’s attribute scope implements AttributeDynamicLookup, the dot syntax resolves to an equivalent subscript expression, allowing attributedString.foregroundColor to replace attributedString[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self].
You can also set an attribute to apply only to part of an attributed string, by applying the attribute to a range, as seen here:
var attributedString = AttributedString("The first month of your subscription is free.")
guard let range = attributedString.range(of: "free") else {return}
attributedString[range].foregroundColor = .greenYou can access portions of the string with unique combinations of attributes by iterating over the string’s runs property.
You can define your own custom attributes by creating types that conform to AttributedStringKey, and collecting them in an AttributeScope. Custom keys should also extend AttributeDynamicLookup, so callers can use dot-syntax to access the attribute.
Creating Attributed Strings with Markdown
You can create an attributed string by passing a standard String or Data instance that contains Markdown to initializers like init(markdown:options:baseURL:). The attributed string creates attributes by parsing the markup in the string.
do {
let thankYouString = try AttributedString(
markdown:"**Thank you!** Please visit our [website](https://example.com)")
} catch {
print("Couldn't parse the string. \(error.localizedDescription)")
}Localized strings that you load from strings files with initializers like init(localized:options:table:bundle:locale:comment:) can also contain Markdown to add styling. In addition, these localized attributed string initializers can apply the replacementIndex attribute, which allows you to determine the range of replacement strings, whose order may vary between languages.
By declaring new attributes that conform to MarkdownDecodableAttributedStringKey, you can add attributes that you invoke by using Apple’s Markdown extension syntax: ^[text](name:value, name:value, …). See the sample code project Building a Localized Food-Ordering App for an example of creating custom attributes and using them with Markdown.
Localized attributed strings can also use the extension syntax to indicate parts of the string where the system can apply automatic grammar agreement. See the initializers that take a localized: parameter for examples of this extension syntax, as used with automatic grammar agreement.
Attribute Scopes
The AttributedString API defines keys for common uses, such as text styling, semantically marking up formattable types like dates and numbers, and hyperlinking. You can find these in the AttributeScopes enumeration, which contains attributes for AppKit, Foundation, SwiftUI, and UIKit.
You can define your own attributes by implementing AttributedStringKey, and reference them by name by collecting them in an AttributeScope.
Topics
Creating an Attributed String
Creating a Localized Attributed String
init(localized:options:table:bundle:locale:comment:)init(localized:options:table:bundle:locale:comment:including:)init(localized:options:table:bundle:locale:comment:including:)String.LocalizationValueAttributedString.FormattingOptionsinit(localized:)init(localized:including:)init(localized:including:)LocalizedStringResource
Creating a Localized Attributed String with a Default Value
init(localized:defaultValue:options:table:bundle:locale:comment:)init(localized:defaultValue:options:table:bundle:locale:comment:including:)init(localized:defaultValue:options:table:bundle:locale:comment:including:)
Creating an Attributed String from Markdown
Creating an Attributed String from a Reference Type
Creating a Duplicate Attributed String
Applying and Modifying Attributes
Using Defined Attributes
Accessing Indices
Accessing Views into the Attributed String
Modifying an Attributed String
Transforming Attributes
transformingAttributes(_:_:)transformingAttributes(_:_:)transformingAttributes(_:_:_:)transformingAttributes(_:_:_:)transformingAttributes(_:_:_:_:)transformingAttributes(_:_:_:_:)transformingAttributes(_:_:_:_:_:)transformingAttributes(_:_:_:_:_:)transformingAttributes(_:_:_:_:_:_:)transformingAttributes(_:_:_:_:_:_:)AttributedString.SingleAttributeTransformer
Accessing Whole-String Attributes
Combining Attributed Strings
Performing Automatic Grammar Agreement
Performing String Interpolation
Encoding and Decoding
Supporting types
Structures
AttributedString.AdaptiveImageGlyphAttributedString.AttributeInvalidationConditionAttributedString.LineHeightAttributedString.LocalizationOptionsAttributedString.MarkdownSourcePositionAttributedString.UTF16ViewAttributedString.UTF8View
Initializers
init(_:)init(localized:defaultValue:options:table:bundle:locale:comment:)init(localized:defaultValue:options:table:bundle:locale:comment:including:)init(localized:defaultValue:options:table:bundle:locale:comment:including:)init(localized:options:)init(localized:options:including:)init(localized:options:including:)init(localized:options:table:bundle:locale:comment:)init(localized:options:table:bundle:locale:comment:including:)init(localized:options:table:bundle:locale:comment:including:)init(transferable:in:)
Instance Methods
inflected(locale:userTermOfAddress:inflectionConcepts:)rangeOfAudioTimeRangeAttributes(intersecting:)removeSubranges(_:)replaceSelection(_:with:)replaceSelection(_:withCharacters:)transform(updating:body:)transform(updating:body:)transform(updating:body:)transform(updating:body:)transform(updating:body:)transformAttributes(in:body:)
Subscripts
Type Aliases
Type Properties
Enumerations
AttributedString.AttributeRunBoundariesAttributedString.TextAlignmentAttributedString.WritingDirection