Search code examples
iosswiftrealmrealm-mobile-platform

RealmSwift: How to properly Adopt to RealmOptionalType protocol on UInt?


I have an object whose one of the properties from the server requires a type to be UInt, My project uses RealmSwift to store data locally once the data is parsed from the server.

Here is the sample use case:

import RealmSwift
import Foundation 

class MediaServerInfo: Object {
private var _hostPort = RealmOptional<UInt>()

}

// MARK: - Adopting to RealmOptionalType

// Here I am trying to adopt the protocol so that the _hostPort above can use RealmOptional<UInt>()

extension UInt: RealmOptionalType {
  public static func className() -> String {
    return "UInt"
  }
}

However, I am getting the following run time error as soon as I enter a page where the above class is used: -

 Terminating app due to uncaught exception 'RLMException', reason: ''RealmOptional<UInt>' is not a valid RealmOptional type.'

Any thoughts on this?


Solution

  • Realm does not support the UInt type. The Realm Cheatsheet shows the supported types along with this from the documentation

    RealmOptional supports Int, Float, Double, Bool, and all of the sized versions of Int (Int8, Int16, Int32, Int64).

    One technique is to store the Int value in Realm as a backing var and leverage a non managed var to be the front.

    class MediaServerInfo: Object {
       private let _hostPort = RealmOptional<Int>()
    
       var hostPort: UInt {
          get {
             let myInt = _hostPort.value ?? 0
             let u = UInt(myInt)
             return u
          }
        
         set {
            let myInt = Int(newValue)
            _hostPort.value = myInt
         }
       }
    }
    

    And use it like this when creating

    let info = MediaServerInfo()
    info.hostPort = UInt(42)
    

    or to read

    let x = info.hostPort