3
0

More than 1 year has passed since last update.

RealmSwift の deprecated warning に対応した

Posted at

事象

先日、久しぶりに RealmSwift のバージョンアップをしたところ、下記のような警告が出るようになってしまいました。

RealmOptional is deprecated: RealmOptional<T> has been deprecated, use RealmProperty<T?> instead.
Use RealmProperty instead

上記の警告を見て、RealmProperty の使い方を覚える必要があるかと思いましたが、実際はもっと良い解決方法が実装されていました。

解決方法

次のようなクラスがあったとした場合、

class Sample {
  let index = RealmOptional<Int>() // ここで警告が出る
}

下記のように直します。

class Sample {
  @Persisted var index: Int?
}

また、主キーにしたい場合や インデックスをつけたい場合は下記のように宣言できます。

class Sample {
  @Persisted(primaryKey: true) var primaryKey: Int?
  @Persisted(indexed: true) var indexedProperty: Int?
}

説明

リリースノートを見ると、RealmSwift のバージョン 10.10.0 から @Persisted プロパティラッパーが使えるようになり、これによって(Objective-C でサポートされていない型では)RealmPropertyRealmOptional は不要になった、というような記載があります。
また、@objc dynamic var で宣言していたプロパティも @Persisted var に置き換えられるようです。主キーやインデックスの設定も簡単になっています。

  • リリースノートより抜粋
Add a new property wrapper-based declaration syntax for properties on Realm Swift object classes. Rather than using @objc dynamic or the RealmProperty wrapper type, properties can now be declared with @Persisted var property: T, where T is any of the supported property types, including optional numbers and collections. This has a few benefits:

- All property types are now declared in the same way. No more remembering that this type requires @objc dynamic var while this other type requires let, and the RealmProperty or RealmOptional helper is no longer needed for types not supported by Objective-C.
- No more overriding class methods like primaryKey(), indexedProperties() or ignoredProperties(). The primary key and indexed flags are set directly in the property declaration with @Persisted(primaryKey: true) var _id: ObjectId or @Persisted(indexed: true) var indexedProperty: Int. If any @Persisted properties are present, all other properties are implicitly ignored.
  • DeepL による日本語訳
Realm Swiftオブジェクトクラスのプロパティに、新しいプロパティラッパーベースの宣言構文を追加しました。objc dynamic や RealmProperty ラッパー型を使う代わりに、プロパティは @Persisted var property で宣言することができるようになりました。ここで T はサポートされている任意のプロパティタイプで、オプションの数値やコレクションを含みます。これにはいくつかの利点があります。

- すべてのプロパティタイプが同じ方法で宣言されるようになりました。この型には @objc dynamic var が必要で、他の型には let が必要だと覚える必要はありませんし、Objective-C でサポートされていない型には RealmProperty や RealmOptional ヘルパーは不要になりました。
- primaryKey()、indexedProperties()、ignoredProperties()などのクラスメソッドをオーバーライドする必要はもうないのです。主キーやインデックス付きのフラグは、プロパティ宣言の中で @Persisted(primaryKey: true) var _id と直接設定されます。ObjectId または @Persisted(indexed: true) var indexedProperty: Int. いずれかの @Persisted プロパティが存在する場合、他のすべてのプロパティは暗黙のうちに無視されます。
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0