This document shows you how to update a resource using a field mask in the
Google Cloud client libraries for Swift to control which fields
on the resource you modify. The examples use a secret from
Secret Manager as a sample resource, and the same concepts apply across
Google Cloud services that follow the [AIP-134 update
specification](https://google.aip.dev/134) and [AIP-161 field mask
specification](https://google.aip.dev/161) on google.aip.dev.

## Before you begin

This document uses the Secret Manager API. To enable this API, follow
the [Secret Manager
quickstart](https://docs.cloud.google.com/secret-manager/docs/create-secret-quickstart).

For complete setup instructions for the Swift client libraries, see
[Quickstart: Get started with Swift](https://docs.cloud.google.com/swift/quickstart.md.txt).

## The `WKTFieldMask` type

A `WKTFieldMask` instance represents a set of symbolic field paths, such as
`paths: ["annotations", "labels"]` or `paths: ["user.display_name", "photo"]`.
You use field masks to specify which fields a read operation returns or which
fields an update operation modifies.

In an update operation, the API modifies only the fields listed in the field
mask and leaves all other fields unchanged. If you provide a resource with
additional modified fields, the API ignores any fields not covered by the mask.
For services that support full resource replacement, you can pass the wildcard
mask `["*"]` to update all fields.

`WKTFieldMask` conforms to `ExpressibleByArrayLiteral`, which lets you specify
field masks in two ways:

- **Array literals:** use array literals such as `updateMask: ["annotations",
  "labels"]` when you know the fields to update at compile time. This style is concise and doesn't require importing `GoogleWKT`.
- **Explicit initializers:** use `WKTFieldMask(paths: myPaths)` when your app computes the list of fields dynamically at runtime from a `[String]` collection. This style requires importing `GoogleWKT` and adding the [`swift-google-wkt`](https://github.com/googleapis/swift-google-wkt) package on GitHub as a dependency.

Field paths use the lowercase, underscore-separated field names from the
protobuf definition relative to the updated resource---for example,
`"version_aliases"` rather than the Swift property name `versionAliases`.

To reset a field to its default value, include the field path in the mask and
leave that field set to its default value on the provided resource.

### Install well-known types for dynamic masks

The `swift-google-wkt` package (`GoogleWKT` module) provides Protocol Buffer
well-known types for Google Cloud APIs, including `WKTFieldMask`. If your
app constructs dynamic field masks using `WKTFieldMask(paths:)`, follow these
steps to add `swift-google-wkt` as a dependency:

1. Add the `swift-google-wkt` package to your `Package.swift` dependencies:

   ```bash
   swift package add-dependency \
       https://github.com/googleapis/swift-google-wkt.git --from 0.6.0
   ```
2. Add the `GoogleWKT` module as a dependency of your target:

   ```bash
   swift package add-target-dependency \
       GoogleWKT TARGET_NAME --package swift-google-wkt
   ```

   Replace `TARGET_NAME` with the name of your target.

## Update fields on a resource

To update specific fields on a secret resource, follow these steps:

1. Add the imports required to use the Secret Manager client
   library:


   ```swift
   import Foundation
   import GoogleCloudSecretManagerV1
   ```

   <br />

2. Define a function that receives the project ID and secret ID as parameters:


   ```swift
   func sample(projectId: String, secretId: String) async throws {
   ```

   <br />

3. Initialize a Secret Manager client and create a secret. When
   you create the secret, both the `labels` and `annotations` dictionaries are
   empty:


   ```swift
   let client = try SecretManagerServiceClient()

   let secret = try await client.createSecret(
     parent: "projects/\(projectId)",
     secretId: secretId,
     secret: Secret().with {
       $0.replication = Replication().with { replication in
         replication.replication = .automatic(Replication.Automatic())
       }
     }
   )
   print("CREATE = \(secret)")
   ```

   <br />

4. Construct a `Secret` object containing the updated `labels` and
   `annotations`, along with the resource `name` and
   [`etag` field](https://docs.cloud.google.com/secret-manager/docs/etags.md.txt). Setting `etag` prevents
   overwriting concurrent updates:


   ```swift
   var labels = secret.labels
   labels["updated"] = "your-label"
   var annotations = secret.annotations
   annotations["updated"] = "your-annotations"

   let updatedSecret = Secret().with {
     $0.name = secret.name
     $0.etag = secret.etag
     $0.labels = labels
     $0.annotations = annotations
   }
   ```

   <br />

5. Call `updateSecret(secret:updateMask:)`, passing an array literal with the
   `annotations` and `labels` field paths to update only those fields:


   ```swift
   let update = try await client.updateSecret(
     secret: updatedSecret,
     updateMask: ["annotations", "labels"]
   )
   print("UPDATE = \(update)")
   ```

   <br />

## Complete code

The following example shows the complete code for this document:

```swift
import Foundation
import GoogleCloudSecretManagerV1

func sample(projectId: String, secretId: String) async throws {
  let client = try SecretManagerServiceClient()

  let secret = try await client.createSecret(
    parent: "projects/\(projectId)",
    secretId: secretId,
    secret: Secret().with {
      $0.replication = Replication().with { replication in
        replication.replication = .automatic(Replication.Automatic())
      }
    }
  )
  print("CREATE = \(secret)")

  var labels = secret.labels
  labels["updated"] = "your-label"
  var annotations = secret.annotations
  annotations["updated"] = "your-annotations"

  let updatedSecret = Secret().with {
    $0.name = secret.name
    $0.etag = secret.etag
    $0.labels = labels
    $0.annotations = annotations
  }

  let update = try await client.updateSecret(
    secret: updatedSecret,
    updateMask: ["annotations", "labels"]
  )
  print("UPDATE = \(update)")
}
```

## What's next

- Learn how to use [paginated operations](https://docs.cloud.google.com/swift/pagination.md.txt).
- Learn how to use [long-running operations](https://docs.cloud.google.com/swift/long-running-operations.md.txt).
- Learn how to [override the default authentication
  credentials](https://docs.cloud.google.com/swift/override-credentials).
- Learn how to [override the default endpoint](https://docs.cloud.google.com/swift/override-endpoint.md.txt).
- Learn how to [override the default retry
  policies](https://docs.cloud.google.com/swift/override-retry-policy).
- Learn how to [override the default polling
  policies](https://docs.cloud.google.com/swift/override-polling-policy).
- Learn how to [enable logging](https://docs.cloud.google.com/swift/enable-logging.md.txt) to troubleshoot requests and responses.
- Learn how to configure [package traits](https://docs.cloud.google.com/swift/package-traits.md.txt) for large client libraries.
- Browse the [Swift Cloud client libraries](https://docs.cloud.google.com/swift/reference.md.txt) reference documentation.