<!--
{
  "availability" : [
    "iOS: 26.0.0 -",
    "iPadOS: 26.0.0 -",
    "macCatalyst: 26.0.0 -",
    "macOS: 26.0.0 -",
    "tvOS: 26.0.0 -",
    "visionOS: 26.0.0 -",
    "watchOS: 26.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftUI",
  "identifier" : "/documentation/SwiftUI/AttributedTextValueConstraint/constrain(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI29AttributedTextValueConstraintP9constrainyyAA0cD10FormattingO23AttributeContainerProxyVy_5ScopeQz0I3KeyQzGzF"
  },
  "title" : "constrain(_:)"
}
-->

# constrain(_:)

Enforce constraints on the attribute.

```
func constrain(_ container: inout Self.Attributes)
```

## Discussion

A function that transforms the [`AttributeKey`](/documentation/SwiftUI/AttributedTextValueConstraint/AttributeKey) on the given `container`
so it represents a formatting that the conforming type defines to be
valid.

This function can generally read any attribute on `container` and it
will produce a value that has been constrained by all
[`AttributedTextValueConstraint`](/documentation/SwiftUI/AttributedTextValueConstraint) listed in the associated text
formatting definition above the constraint reading the attribute.

Consider the following example:

```
struct NoEqualForegroundAndBackground: AttributedTextValueConstraint {
    typealias Scope = MyTextFormattingDefinition.Scope
    typealias AttributeKey = AttributeScopes.SwiftUIAttributes.BackgroundColorAttribute

    func constrain(
        _ container: inout Attributes
    ) {
        if let color = container.foregroundColor,
           container.backgroundColor == color
        {
            container.backgroundColor = nil
        }
    }
}
```

When this constrain function accesses `container.foregroundColor`, the
system establishes that the background color depends on the foreground
color. At that time, it checks if the
[`AttributedTextFormattingDefinition`](/documentation/SwiftUI/AttributedTextFormattingDefinition) this constraint is part of
defines constraints on the foreground color *above*
`NoEqualForegroundAndBackground` and applies them. Thus, when
the access to `container.foregroundColor` returns, this function reads
the constrained value.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)