A value type for a string with associated attributes for portions of its text.
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:
```swift
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:
```swift
attributedString[AttributeScopes.AppKitAttributes.ForegroundColorAttribute.self] = .yellow
```
Because an ``AttributedString`` supports dynamic member lookup — as described under
[Attributes](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/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:
```swift
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:
```swift
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.
```swift
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``.
Members (39)
get · iOS 15.0+
characters
TypeScript
get characters(): AttributedString_CharacterView
Swift declaration
var characters: AttributedString.CharacterView { get set }
The characters of the attributed string, as a view into the underlying string.
Use the ``AttributedString/characters`` view when you want to look for specific string
content. You can then use the resulting ranges to set attributes for specific parts of
the ``AttributedString``.
You can also use this property to mutate the attributed string, using
`RangeReplaceableCollection` methods, such as `insert(_:at:)` and `append(_:)`.
Inserted characters inherit any attributes present at the insertion point.
set · iOS 15.0+
characters
TypeScript
set characters(value: AttributedString_CharacterView)
Swift declaration
var characters: AttributedString.CharacterView { get set }
The characters of the attributed string, as a view into the underlying string.
Use the ``AttributedString/characters`` view when you want to look for specific string
content. You can then use the resulting ranges to set attributes for specific parts of
the ``AttributedString``.
You can also use this property to mutate the attributed string, using
`RangeReplaceableCollection` methods, such as `insert(_:at:)` and `append(_:)`.
Inserted characters inherit any attributes present at the insertion point.
Creates an attributed string from the contents of a specified URL that contains Markdown-formatted data, using the provided options.
- Parameters:
- url: The URL to load Markdown-formatted data from.
- options: Options that affect how the initializer interprets formatting in the Markdown string. This parameter defaults to no options.
- baseURL: The base URL to use when resolving Markdown URLs. The initializer treats URLs as being relative to this URL. If this value is `nil`, the initializer doesn't resolve URLs. The default is `nil`.
If your source string includes custom attributes defined by conformers to
``MarkdownDecodableAttributedStringKey`` and used with Apple's markdown extension syntax,
be sure to include the ``NSAttributedStringMarkdownParsingOptions/allowsExtendedAttributes``
option. Otherwise, the initializer doesn't parse these attributes.
get · iOS 15.0+
startIndex
TypeScript
get startIndex(): AttributedString_Index
Swift declaration
var startIndex: AttributedString.Index { get }
The position of the first character in a nonempty attributed string.
In an empty string, `startIndex` is equal to `endIndex`.
Sets the attributed string's attributes to those in a specified attribute container.
- Parameter attributes: The attribute container with the attributes to apply.
Creates an attributed string from the specified string literal, with no attributes.
- Parameter value: The string literal that provides the attributed string's initial content.
get · iOS 15.0+
unicodeScalars
TypeScript
get unicodeScalars(): AttributedString_UnicodeScalarView
Swift declaration
var unicodeScalars: AttributedString.UnicodeScalarView { get set }
The Unicode scalars of the attributed string, as a view into the underlying string.
Use this property when you want to split the attributed string by Unicode scalar instead
of grapheme cluster. This is useful when you need to carefully control insertion points
or render the content.
You can also use this property to mutate the attributed string, using
`RangeReplaceableCollection` methods, such as `insert(_:at:)` and `append(_:)`.
Inserted characters inherit any attributes present at the insertion point.
set · iOS 15.0+
unicodeScalars
TypeScript
set unicodeScalars(value: AttributedString_UnicodeScalarView)
Swift declaration
var unicodeScalars: AttributedString.UnicodeScalarView { get set }
The Unicode scalars of the attributed string, as a view into the underlying string.
Use this property when you want to split the attributed string by Unicode scalar instead
of grapheme cluster. This is useful when you need to carefully control insertion points
or render the content.
You can also use this property to mutate the attributed string, using
`RangeReplaceableCollection` methods, such as `insert(_:at:)` and `append(_:)`.
Inserted characters inherit any attributes present at the insertion point.
Merges the attributed string's attributes with those in a specified attribute container.
- Parameters:
- attributes: The attribute container with the attributes to merge.
- mergePolicy: A policy to use when resolving conflicts between this string's attributes and those in `attributes`.
mutating func replaceAttributes(_ attributes: AttributeContainer, with others: AttributeContainer)
Replaces occurrences of attributes in one attribute container with those in another attribute container.
- Parameters:
- attributes: The existing attributes to replace.
- others: The new attributes to apply.
init(from decoder: any Decoder, configuration: AttributeScopeCodableConfiguration) throws
Creates a new instance by retrieving the instance's data from the specified decoder with help from the provided configuration.
- Parameters:
- decoder: The decoder to read data from.
- configuration: A decoding configuration instance that provides additional information necessary for decoding.
get · iOS 15.0+
runs
TypeScript
get runs(): AttributedString_Runs
Swift declaration
var runs: AttributedString.Runs { get }
The attributed runs of the attributed string, as a view into the underlying string.
Runs begin and end when the attributes for the characters change. Use this property to
iterate over the runs with `for`-`in` syntax.
get · iOS 26.0+
utf8
TypeScript
get utf8(): AttributedString_UTF8View
Swift declaration
var utf8: AttributedString.UTF8View { get }
A view of the attributed string’s contents as a collection of UTF-8 code units.
get · iOS 26.0+
utf16
TypeScript
get utf16(): AttributedString_UTF16View
Swift declaration
var utf16: AttributedString.UTF16View { get }
A view of the attributed string’s contents as a collection of UTF-16 code units.
func encode(to encoder: any Encoder, configuration: AttributeScopeCodableConfiguration) throws
Encodes the value into the specified encoder with help from the provided configuration.
- Parameters:
- encoder: The encoder to write data to.
- configuration: An encoding configuration instance that provides additional information necessary for encoding.
get · iOS 15.0+
endIndex
TypeScript
get endIndex(): AttributedString_Index
Swift declaration
var endIndex: AttributedString.Index { get }
The string's past-the-end position — the position one greater than the last valid subscript argument.
In an empty string, `endIndex` is equal to `startIndex`.
Creates an attributed string from a Markdown-formatted string using the provided options.
- Parameters:
- markdown: The string that contains the Markdown formatting.
- options: Options that affect how the initializer interprets formatting in the Markdown string. This parameter defaults to no options.
- baseURL: The base URL to use when resolving Markdown URLs. The initializer treats URLs as being relative to this URL. If this value is `nil`, the initializer doesn't resolve URLs. The default is `nil`.
If your source string includes custom attributes defined by conformers to
``MarkdownDecodableAttributedStringKey`` and used with Apple's markdown extension syntax,
be sure to include the ``NSAttributedStringMarkdownParsingOptions/allowsExtendedAttributes``
option. Otherwise, the initializer doesn't parse these attributes.
Creates an attributed string from Markdown-formatted data using the provided options.
- Parameters:
- markdown: The ``Data`` instance that contains the Markdown formatting.
- options: Options that affect how the initializer interprets formatting in the Markdown string. This parameter defaults to no options.
- baseURL: The base URL to use when resolving Markdown URLs. The initializer treats URLs as being relative to this URL. If this value is `nil`, the initializer doesn't resolve URLs. The default is `nil`.
If your source string includes custom attributes defined by conformers to
``MarkdownDecodableAttributedStringKey`` and used with Apple's markdown extension syntax,
be sure to include the ``NSAttributedStringMarkdownParsingOptions/allowsExtendedAttributes``
option. Otherwise, the initializer doesn't parse these attributes.
Process automatic grammar agreement and formatting attributes.
- Parameters:
- locale: The locale used for formatting the string. It also specifies
the language used for automatic grammar agreement, unless overridden
with the `languageIdentifier` attribute.
- userTermOfAddress: The user's preferred term of address, if the user
has set one. A value of `nil` indicates no preference, in which case
the inflection alternative will be used for strings that address the
the user. Default value is `.currentUser`.
- inflectionConcepts: A list of objects providing additional hints for
automatic grammar agreement, such as terms of address for people who
are mentioned, or phrases with which the string has to grammatically
agree.
Arguments that were previously formatted in the string must be annotated
with the following attributes:
- `replacementIndex`, set to the index of the format specifier.
- `localizedNumericArgument`, if the argument was numeric, must also be
set to the original value of the argument.
If not all arguments are properly annotated, the `agreeWithArgument` and
`inflect` attributes may not work properly and behavior is undefined.
method · iOS 15.0+
inflected
TypeScript
inflected(): AttributedString
Swift declaration
func inflected() -> AttributedString
Applies automatic grammar agreement inflection rules to the attributed string and returns the result.
- Returns: An attributed string that represents the effect of applying inflection rules to the source attributed string.
Creates an attributed string by looking up a localized string from the app's bundle, using a default value if necessary.
- Parameters:
- key: The key for a string in the table that `table` identifies.
- defaultValue: The localized string for the development locale. For other locales, the string uses this value if a localized string for `key` isn't found in the table.
- options: Options that affect the handling of attributes.
- table: The bundle's string table to search. If `table` is `nil` or is an empty string, the method attempts to use the table in `Localizable.strings`. The default is `nil`.
- bundle: The bundle to use for looking up strings. If `nil`, an app searches its main bundle. The default is `nil`.
- locale: The locale of the localized string to retrieve. If `nil`, this initializer uses the current locale. The default is `nil`.
- comment: The comment to place above the key-value pair in the strings file. This parameter provides the translator with some context about the localized string's presentation to the user.
Use this initializer instead of ``AttributedString/init(localized:options:table:bundle:locale:comment:)-8dlnl``
if you prefer to use a symbolic string key, rather than use the development language's string as the key.
Creates an attributed string by looking up a localized string from the app's bundle.
- Parameters:
- key: The key for a string in the table that `table` identifies.
- options: Options that affect the handling of attributes.
- table: The bundle's string table to search. If `table` is `nil` or is an empty string, the method attempts to use the table in `Localizable.strings`. The default is `nil`.
- bundle: The bundle to use for looking up strings. If `nil`, an app searches its main bundle. The default is `nil`.
- locale: The locale of the localized string to retrieve. If `nil`, this initializer uses the current locale. The default is `nil`.
- comment: The comment to place above the key-value pair in the strings file. This parameter provides the translator with some context about the localized string's presentation to the user.
To create localizable attributed strings, use Markdown syntax in your strings files.
The following example shows a string from a Spanish localization:
```other
"_Please visit our [website](https://www.example.com)._" = "_Visita nuestro [sitio web](https://www.example.com)._";
```
You load this string with one of the initializers that takes `localized` as its first
parameter, like the following:
```swift
let visitString = AttributedString(localized: "_Please visit our [website](https://www.example.com)._")
```
The resulting attributed string contains an `inlinePresentationIntent` attribute to apply
the emphasized presentation intent over the entire string. It also applies the `link`
attribute to the text `sitio web`. User interface frameworks like SwiftUI and UIKit can
then use these attributes when presenting the text to the user.
### Applying Automatic Grammar Agreement
To apply the automatic grammar agreement feature when loading a localized string, use
Apple's Markdown extension syntax: `^[text to inflect](inflect: true)`.
Creates a localized attributed string from a localized string resource.
- Parameter resource: A ``LocalizedStringResource`` that provides the localization key, table, bundle, and locale.
Call this initializer to look up the localization indicated by `resource`. Alter the
resource's locale prior to calling this method if you want to localize this string in a
different locale than the process that created the ``LocalizedStringResource``.
The attributed string contains attributes of type
`FoundationAttributes.LocalizedStringArgumentAttributes` to indicate runs containing
formatted text, such as localized numbers or dates.
mutating func transform<E>(updating ranges: [Range<AttributedString.Index>], body: (inout AttributedString) throws(E) -> Void) throws(E) -> [Range<AttributedString.Index>]? where E : Error
Tracks the location of the provided ranges throughout the mutation closure, returning a new, updated range that represents the same effective locations after the mutation
- Parameters:
- ranges: Ranges to track throughout the `body` block.
- body: A mutating operation, or set of operations, to perform on this `AttributedString`.
- Returns: the updated `Range`s that are valid after the mutation has been performed or `nil` if the mutation performed does not allow for tracking to succeed (such as replacing the provided inout variable with an entirely different `AttributedString`). When the return value is non-`nil`, the returned array is guaranteed to be the same size as the provided array with updated ranges at the same indices as their respective original ranges in the input array.
mutating func transform<E>(updating range: Range<AttributedString.Index>, body: (inout AttributedString) throws(E) -> Void) throws(E) -> Range<AttributedString.Index>? where E : Error
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.
- Parameters:
- range: A range to track throughout the `body` block.
- body: A mutating operation, or set of operations, to perform on this `AttributedString`.
- Returns: the updated `Range` that is valid after the mutation has been performed, or `nil` if the mutation performed does not allow for tracking to succeed (such as replacing the provided inout variable with an entirely different `AttributedString`).
mutating func transform<E>(updating ranges: inout [Range<AttributedString.Index>], body: (inout AttributedString) throws(E) -> Void) throws(E) where E : Error
Tracks the location of the provided ranges throughout the mutation closure, updating them to new ranges that represent the same effective locations after the mutation.
If updating the provided ranges is not possible (tracking failed) then this function will fatal error. Use the `Optional`-returning variants to provide custom fallback behavior.
- Parameters:
- ranges: A list of ranges to track throughout the `body` closure. The updated array (after the function is called) is guaranteed to be the same size as the provided array. Updated ranges are located at the same indices as their respective original ranges in the input `ranges` array.
- body: A mutating operation, or set of operations, to perform on the value of `self`. The value of `self` is provided to the closure as an `inout AttributedString` that the closure should mutate directly. Do not capture the value of `self` in the provided closure - the closure should mutate the provided `inout` copy.
Omit the output parameters from the call. The result contains $ret and $out, with ranges inside $out.
mutating func transform<E>(updating range: inout Range<AttributedString.Index>, body: (inout AttributedString) throws(E) -> Void) throws(E) where E : Error
Tracks the location of the provided range throughout the mutation closure, updating the provided range to one that represents the same effective locations after the mutation.
If updating the provided range is not possible (tracking failed) then this function will fatal error. Use the `Optional`-returning variants to provide custom fallback behavior.
- Parameters:
- range: A range to track throughout the `body` closure.
- body: A mutating operation, or set of operations, to perform on the value of `self`. The value of `self` is provided to the closure as an `inout AttributedString` that the closure should mutate directly. Do not capture the value of `self` in the provided closure - the closure should mutate the provided `inout` copy.
Omit the output parameters from the call. The result contains $ret and $out, with range inside $out.
Creates a new attributed string with the given `String` value associated with the given
attributes.
- Parameters:
- string: A string to add attributes to.
- attributes: Attributes to apply to `string`.
Creates a new attributed string with the given `Substring` value associated with the given
attributes.
- Parameters:
- substring: A substring to add attributes to.
- attributes: Attributes to apply to `substring`.
init<S>(_ elements: S, attributes: AttributeContainer = .init()) where S : Sequence, S.Element == Character
Creates an attributed string from a character sequence and an attribute container.
- Parameters:
- elements: A character sequence that provides the textual content for the attributed string.
- attributes: Attributes to apply to the textual content.
subscript(indices: RangeSet<AttributedString.Index>) -> DiscontiguousAttributedSubstring { get set }
Returns a discontiguous substring of this discontiguous attributed string using a set of ranges to indicate the discontiguous substring bounds.
- Parameter indices: A set of ranges that indicate the bounds of the discontiguous substring to return.
Creates a value-type attributed string from a reference type.
- Parameter nsStr: The ``NSAttributedString`` to convert.
This initializer includes all attribute scopes defined by the SDK, such as
`FoundationAttributes`, `SwiftUIAttributes`, and `AccessibilityAttributes`. To use
third-party attribute scopes, use the initializers ``AttributedString/init(_:including:)-9no47``
or ``AttributedString/init(_:including:)-puv0``.
Creates an attributed string from a discontiguous attributed substring.
- Parameter substring: A discontiguous attributed substring to create the new attributed string from.