Skip to content

Instantly share code, notes, and snippets.

@uruly
Last active July 16, 2020 05:35
Show Gist options
  • Save uruly/a799e5f4cdafbe9585945d7506f93780 to your computer and use it in GitHub Desktop.
Save uruly/a799e5f4cdafbe9585945d7506f93780 to your computer and use it in GitHub Desktop.
Realm マイグレーション処理用
//
// RealmMigration.swift
//
// Created by Reo on 2020/07/16.
// Copyright © 2020 uruly.xyz. All rights reserved.
//
import UIKit
import RealmSwift
final class RealmMigration {
static let shared = RealmMigration()
private let schemaVersion: UInt64 = 2
private lazy var configuration: Realm.Configuration = {
var configuration = Realm.Configuration(schemaVersion: schemaVersion, migrationBlock: migrationBlock)
return configuration
}()
private lazy var migrationBlock: RealmSwift.MigrationBlock? = {
return .init { [weak self] (migration, oldSchemaVersion) in
self?.migration(migration, from: oldSchemaVersion)
}
}()
private func migration(_ migration: Migration, from oldSchemaVersion: UInt64) {
if oldSchemaVersion < 2 {
migrationTo2(migration)
}
}
func configure() {
Realm.Configuration.defaultConfiguration = configuration
}
}
// バージョンごとのマイグレーション処理
extension RealmMigration {
private func migrationTo2(_ migration: Migration) {
migration.enumerateObjects(ofType: "Color") { old, new in
guard
let hue: CGFloat = old?["hue"] as? CGFloat,
let saturation: CGFloat = old?["saturation"] as? CGFloat,
let brightness: CGFloat = old?["brightness"] as? CGFloat,
let alpha: CGFloat = old?["alpha"] as? CGFloat else {
fatalError("Migration is Failed.")
}
new!["hue"] = Float(hue)
new!["saturation"] = Float(saturation)
new!["brightness"] = Float(brightness)
new!["alpha"] = Float(alpha)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment