---
title: "encodeIfPresent(_:forKey:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/keyedencodingcontainerprotocol/encodeifpresent(_:forkey:)-1r22b"
---

# encodeIfPresent(_:forKey:)

Encodes the given value for the given key if it is not nil.

## Declaration

```swift
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Self.Key) throws
```

## Parameters

- `value`: The value to encode.
- `key`: The key to associate the value with.

## Discussion

Discussion note: EncodingError.invalidValue if the given value is invalid in the current context for this format.
