UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.