Define a Realm Object Schema - Swift SDK¶
On this page
- Define a New Object Type
- Declare Properties
- Specify an Optional/Required Property
- Specify a Primary Key
- Index a Property
- Ignore a Property
- Declare Enum Properties
- Declare Relationship Properties
- Define a To-One Relationship Property
- Define a To-Many Relationship Property
- Define an Inverse Relationship Property
- Define an Embedded Object Property
Define a New Object Type¶
Class names are limited to a maximum of 57 UTF-8 characters.
For reference on which types Realm Database supports for use as properties, see Supported Property Types - Swift SDK.
Property names are limited to a maximum of 63 UTF-8 characters.
Specify an Optional/Required Property¶
Specify a Primary Key¶
Primary keys enforce uniqueness among objects in a realm.
As long as an object is managed by a realm, that object's primary key value is immutable.
Index a Property¶
Indexes make queries using equality and IN operators faster in exchange for slightly slower writes. Indexes take up more space in the realm file. It’s best to only add indexes when optimizing the read performance for specific situations.
Realm supports indexing for string, integer, boolean,
New in version 10.8.0:
Ignore a Property¶
Ignored properties behave exactly like normal properties. They can’t be used in queries and won’t trigger Realm notifications. You can still observe them using KVO.
Realm automatically ignores read-only properties.
Declare Enum Properties¶
Declare Relationship Properties¶
Define a To-One Relationship Property¶
A to-one relationship maps one property to a single instance of another object type. For example, you can model a person having at most one companion dog as a to-one relationship.
Define a To-Many Relationship Property¶
A to-many relationship maps one property to zero or more instances of another object type. For example, you can model a person having any number of companion dogs as a to-many relationship.
Define an Inverse Relationship Property¶
An inverse relationship property is an automatic backlink relationship. Realm Database automatically updates implicit relationships whenever an object is added or removed in a corresponding to-many list or to-one relationship property. You cannot manually set the value of an inverse relationship property.
Define an Embedded Object Property¶
An embedded object exists as nested data inside of a single, specific parent object. It inherits the lifecycle of its parent object and cannot exist as an independent Realm object. Realm automatically deletes embedded objects if their parent object is deleted or when overwritten by a new embedded object instance.
When you delete a Realm object, any embedded objects referenced by that object are deleted with it. If you want the referenced objects to persist after the deletion of the parent object, your type should not be an embedded object at all. Use a regular Realm object with a to-one relationship instead.