How to add complex values to SwiftData models

To include complex values such as structures, enumerations or other value types to a SwiftData model, make sure that they conform to the Codable protocol.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 10/25/2023 at 10:59
Last Updated on 10/27/2023 at 11:46
<p>Three flowers that represent Swift, SwiftData and Xcode. Beneath them sits the text "Complex Values."</p>

To include complex values such as structures, enumerations or other value types to a SwiftData model, make sure that they conform to the Codable protocol.

SubscribeCheck out our SwiftData Quick Start Guide

Step One: Create the Model

<p>A screenshot of Xcode showing a completed model in the SampleSwiftDataModel.swift file.</p>

Consult the tutorial below to learn how to setup a SwiftData model.

How to create a SwiftData Model in Swift

Step Two: Create the Complex Value

<p>A screenshot of Xcode showing a struct that uses the codable protocol.</p>

Create a new struct, enumeration or complex value and make sure that it uses the Codable protocol.

Step Three: Add to the SwiftData Model

<p>A screenshot of Xcode showing how we added a complex value to the model and init function.</p>

Add the complex value to the SwiftData model and init function.

If you do not wish for the value to persist, add a @Transient annotation and a default value.

How to create a SwiftData model variable that does not persist

Looking to learn more about things you can do with SwiftData, Swift or XCode ?

Consult our quick start guide or search our blog to find educational content on learning how to use SwiftData, Swift or XCode.

Consult our SwiftData Quick Start GuideSearch our Blog

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe