<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftUI",
  "identifier" : "/documentation/SwiftUI/View/environment(_:_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI4ViewPAAE11environmentyQrs15WritableKeyPathCyAA17EnvironmentValuesVqd__G_qd__tlF"
  },
  "title" : "environment(_:_:)"
}
-->

# environment(_:_:)

Sets the environment value of the specified key path to the given value.

```
nonisolated func environment<V>(_ keyPath: WritableKeyPath<EnvironmentValues, V>, _ value: V) -> some View
```

## Parameters

`keyPath`

A key path that indicates the property of the
[`EnvironmentValues`](/documentation/SwiftUI/EnvironmentValues) structure to update.

`value`

The new value to set for the item specified by `keyPath`.

## Return Value

A view that has the given value set in its environment.

## Discussion

Use this modifier to set one of the writable properties of the
[`EnvironmentValues`](/documentation/SwiftUI/EnvironmentValues) structure, including custom values that you
create. For example, you can set the value associated with the
[`truncationMode`](/documentation/SwiftUI/EnvironmentValues/truncationMode) key:

```
MyView()
    .environment(\.truncationMode, .head)
```

You then read the value inside `MyView` or one of its descendants
using the [`Environment`](/documentation/SwiftUI/Environment) property wrapper:

```
struct MyView: View {
    @Environment(\.truncationMode) var truncationMode: Text.TruncationMode

    var body: some View { ... }
}
```

SwiftUI provides dedicated view modifiers for setting most
environment values, like the [`truncationMode(_:)`](/documentation/SwiftUI/View/truncationMode(_:))
modifier which sets the [`truncationMode`](/documentation/SwiftUI/EnvironmentValues/truncationMode) value:

```
MyView()
    .truncationMode(.head)
```

Prefer the dedicated modifier when available, and offer your own when
defining custom environment values, as described in
[`Entry()`](/documentation/SwiftUI/Entry()).

This modifier affects the given view,
as well as that view’s descendant views. It has no effect
outside the view hierarchy on which you call it.

---

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)