Structure
AttributedString
@dynamicMemberLookup struct AttributedString
Overview
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(_:)-6gvcp method, you can omit the explicit use of an AttributeContainer and just set the attribute by its type:
attributedString[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self] = .yellow
Because 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 = .green
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 = .green
You 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:)-52n3u. 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:)-8dlnl can also contain Markdown to add styling. In addition, these localized attributed string initializers can apply the AttributeScopes.FoundationAttributes.ReplacementIndexAttribute 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, …).
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
Structures
struct AttributeInvalidationConditionstruct CharacterViewA view into the underlying storage of the attributed string, as Unicode characters.struct IndexA type that represents the position of a character or code unit within an attributed string.struct RunsAn iterable view into segments of the attributed string, each of which indicates where a run of identical attributes begins or ends.struct SingleAttributeTransformerA type that transforms an attribute by altering its range or value, or by replacing it entirely.struct UTF16ViewA view of an attributed string’s contents as a collection of UTF-16 code units.struct UTF8ViewA view of an attributed string’s contents as a collection of UTF-8 code units.struct UnicodeScalarViewA view into the underlying storage of the attributed string, as Unicode scalars.
Operators
static +(_:_:)Concatenates two attributed strings.static +=(_:_:)Appends an attributed string to another attributed string.
Initializers
init()Creates an empty attributed string.init(_:)Creates an attributed string from an attributed substring.init(_:attributes:)Creates a new attributed string with the givenStringvalue associated with the given attributes.
Instance Methods
func append(some AttributedStringProtocol)Appends a string to the attributed string.func insert(some AttributedStringProtocol, at: AttributedString.Index)Inserts the specified string at a specific index in the attributed string.func removeSubrange(some RangeExpression<AttributedString.Index>)Removes a range of characters from the attributed string.func removeSubranges(RangeSet<AttributedString.Index>)Removes the elements at the given indices.func replaceSubrange(some RangeExpression<AttributedString.Index>, with: some AttributedStringProtocol)Replaces the contents in a range of the attributed string.func transform(updating:body:)Tracks the location of the provided range throughout the mutation closure, returning a new, updated range that represents the same effective locations after the mutation.func transformingAttributes(_:_:)Returns an attributed string by calling a closure that transforms one attribute of a source attributed string.func transformingAttributes(_:_:_:)Returns an attributed string by calling a closure that transforms two attributes of a source attributed string.func transformingAttributes(_:_:_:_:)Returns an attributed string by calling a closure that transforms three attributes of a source attributed string.func transformingAttributes(_:_:_:_:_:)Returns an attributed string by calling a closure that transforms four attributes of a source attributed string.func transformingAttributes(_:_:_:_:_:_:)Returns an attributed string created by calling a closure that transforms five attributes of a source attributed string.
Enumerations
enum AttributeMergePolicyA type that defines the behavior when merging attributes.enum AttributeRunBoundariesenum WritingDirectionThe writing direction of a piece of text.
Default Implementations
Relationships
Conforms To
AttributedStringAttributeMutationAttributedStringProtocolSwift.CopyableSwift.CustomStringConvertibleSwift.EquatableSwift.EscapableSwift.ExpressibleByExtendedGraphemeClusterLiteralSwift.ExpressibleByStringLiteralSwift.ExpressibleByUnicodeScalarLiteralSwift.HashableSwift.SendableSwift.SendableMetatype