user3686123
user3686123

Reputation: 295

How to assign nil to RealmOptional<Int>

I have model class something like this and don't know how to assign an swift optional value to RealmOptional, it force me to unwrap the optional. Why I need to unwrap the optional before assign to RealmOptional.

What will be the best option to assign a swift optional to RealmOptional.

import Foundation
import RealmSwift

class Menu:Object {

    var id = RealmOptional<Int>()

    func initWithJSON(json: Any) {

        let jsonResult = json as! [String: Any]

        id              = jsonResult["id"] as? RealmOptional<Int>

    }
}

Below the error message that force me to unwrap the optional.

enter image description here

Upvotes: 1

Views: 1814

Answers (2)

David Pasztor
David Pasztor

Reputation: 54785

You shouldn't directly modify a RealmOptional property, you should always modify its value property, which holds the underlying Optional value. For this reason, you should always declare RealmOptionals as immutable, since RealmOptional is a reference type, so you can still modify its value property without having to modify the actual reference.

class Menu:Object {

    let id = RealmOptional<Int>()

    func initWithJSON(json: Any) {
        let jsonResult = json as! [String: Any]
        id.value = jsonResult["id"] as? Int
    }
}

Or even better, make RealmOptional conform to Codable and then you'll be able to make Menu conform to it as well.

extension RealmOptional: Codable where Value:Codable {
    public convenience init(from decoder: Decoder) throws {
        do {
            let value = try decoder.singleValueContainer().decode(Value.self)
            self.init(value)
        } catch {
            if case DecodingError.valueNotFound(_, _) = error {
                self.init(nil)
            } else {
                throw error
            }
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(value)
    }
}

class Menu: Codable {
    let id = RealmOptional<Int>()
}

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100551

You can try to

id.value = (jsonResult["id"] as? Int  ?? 0 ) 

Declaring

var id = RealmOptional<Int>()

is not an optional it will if you declared it like

var id:RealmOptional<Int>?

it's like doing

  var str = String()

override func viewDidLoad() {

    super.viewDidLoad() 

    str = "" as? String  // will give error 

Upvotes: 0

Related Questions