title: best way to rename a class in Realm swift
body: <p>I use a "common" library in my iOS project. This library creates a Realm database. So far, I've been using this library on only iOS projects. I want to now use that same library with a macOS project. It's <code>Foundation</code> based, and doesn't use <code>UIKit</code>, so why not?</p>
  
  <p>Here's the problem: I have a Realm class named <strong><code>Collection</code></strong></p>
  
  <p><code>Collection</code> is also the name of a standard Swift protocol.</p>
  
  <p>While I've been able to get away with this name collision on my iOS project, for some reason, I can't do the same on my MacOS project -- it creates a name-collection.</p>
  
  <p>I read about this notation that can be used like this:</p>
  
  <pre><code>@objc(SpecialCollection)
  class Collection: Realm.Object {
     let items: List&lt;ItemObject&gt;
     let name: String
     let url: String
    ....
  }
  </code></pre>
  
  <p>So, this solves the name-collision problem. In ObjC, the name will be something different, but in Swift, I don't need to change anything.</p>
  
  <p>This is all well and good except for my local Realm database. I have a lot of <code>Collection</code> objects that should be renamed to <code>SpecialCollection</code> (since Realm uses ObjC underneath Swift). I'd like to perform a migration to do this, but apparently there isn't a supported way to do this yet? I noticed tickets on github about this issue being "watched", but unfortunately, there still exists no published solution to fix this problem.</p>
  
  <p>All of my <code>Collection</code> objects contain <code>List</code> objects (hence the name). So, I tried to run an enumeration on all of the <code>Collection</code> objects in a migration... I would just take the older object, and create a new object with the new name, like this:</p>
  
  <pre><code> migration.enumerateObjects(ofType: "Collection", { (oldObject, _) in
      migration.create("SpecialCollection", value: oldObject)
   }
  </code></pre>
  
  <p>But since <code>oldObject</code> has a list of other objects, Realm's migration will try and create all the items in any <code>List</code> objects... which can't be done, because it creates objects with the same <code>primaryKey</code> value (causing a crash).</p>
  
  <p>So, I can't keep the old name (Collection), and I can't convert to the new name, <strong>and</strong> I can't just trash the user's data. So, I'm truly at an impasse.</p>
  
  <p>Blockquote</p>
  
  <p>I tried to modify <code>oldObject</code> before creating the new object, but you can't change <code>oldObject</code> in a migration.</p>
  
  <p>The only rule is that the old data has to be preserved, I can't just destroy the user's realm here.</p>
  
  <p>Thanks for any help in this. It is greatly appreciated.</p>