Search code examples
swiftrealm

RealmSwift with enum list


I have an enum with some strings case

public enum UserPermission: String, Decodable {
    case userManagement = "USER_MANAGEMENT"
    case contactManagement = "CONTACT_MANAGEMENT"
    case userV2 = "USER_V2.1"
}

@objcMembers final public class MyModel: Object, Decodable {

    public var permissionCollection = List<UserPermission>()

    public dynamic var rawRole: String? = nil

    private enum CodingKeys : String, CodingKey {
        case permissionCollection = "permission_collection"
    }

    convenience public init(permissionCollection: String) {
        self.init()
        self.permissionCollection = permissionCollection
    }

    public required convenience init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let rawRermissionCollection = try container.decode(String.self, forKey: .permissionCollection)
        self.init(permissionCollection: permissionCollection)
    }

}

I have an error Type 'UserPermission' does not conform to protocol 'RealmCollectionValue'

In the data model I need to store the enum as a list using realm. Have someone to know how I could do this?


Solution

  • Realm's List can only store elements that are either Object subclasses or one of the supported property types of Realm (such as Int, String, etc.). Realm doesn't support storing enum values, so you cannot store them in a List either.

    One alternative is to store the rawValue of your enum, since it has a rawValue of type String, which can be stored in Realm.