TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to change property type with custom migration?

Forums > Swift

Hi all! I googled quite a lot and read https://www.hackingwithswift.com/quick-start/swiftdata/how-to-create-a-complex-migration-using-versionedschema again, but I still can not find a way to change the data type of a class, e.g.

from

@Model
final class Race {
    var timestamp: Date = Date()

    var cc: Int = 150
}

to

@Model
final class Race {
    var timestamp: Date = Date()

    var cc: String = "150"
}

what should I fill in willMigrate block?

static let migrateV1toV2 = MigrationStage.custom(
    fromVersion: RacesSchemaV1.self,
    toVersion: RacesSchemaV2.self,
    willMigrate: { context in
        let items = try? context.fetch(FetchDescriptor<RacesSchemaV1.Race>())

         // TODO: what to do to change the type of cc?

        try? context.save()
    }, didMigrate: nil
)

Thanks in advance!

2      

Not 100% sure if this is the best way and if it works but try something like that. Apologies for any typos as code added right here :)

static var itemsToMigrate: [Race] = []

static let migrateV1toV2 = MigrationStage.custom(
    fromVersion: RacesSchemaV1.self,
    toVersion: RacesSchemaV2.self,
    willMigrate: { context in
    // so you take all your items from old version
        itemsToMigrate = try? context.fetch(FetchDescriptor<RacesSchemaV1.Race>())
    }, didMigrate { context in
      // loop through the items in old version, take each item cc info and add to updated version and converting it to String.
        for item in itemsToMigrate {
          context.insert(RacesSchemaV2.Race(cc: String(item.cc))) // for safety may be add check for type conversion to String...
        }

        try? context.save()
  }
)

4      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.