Unwrap Optional Value from Dictionary

182 Views Asked by At

I'm having an issue unwrapping a value thats stored in an Ordered Dictionary. I created a reproducible example.

I'm pulling data from a database and the format looks like ["isCompleted": Optional(false), "_id": Optional("62cef664008fd87e00e60667"), "body": Optional("run")]

I then create a Document object and store that in a list of those objects (in this sample there is only one).

I'm trying to display the value of the Ordered Dictionary in the Document Object, but can't seem to unwrap the Optional value no matter what I try.

import SwiftUI
import OrderedCollections

class ContentViewModel : ObservableObject {
    
    var orderedDict = OrderedDictionary<String, Any?>()
    @Published var docsList: [Document] = []

    
    init() {
        let doc: [String: Any?] = ["isCompleted": false, "_id": "62cef664008fd87e00e60667", "body": "run"]
        
        for (key, value) in doc {
            self.orderedDict[key] = value
        }
        
        self.docsList.append(Document(id: UUID().description, value: self.orderedDict))
        
    }
}

struct ContentView: View {
    
    @StateObject var viewModel = ContentViewModel()
    
    var body: some View {
        
        ForEach(viewModel.docsList, id: \.self) { doc in
            
            if let val = doc.value["isCompleted"] {
                Text(val.debugDescription)
            }
            
            if(doc.value["isCompleted"] != nil) {
                Text(doc.value["isCompleted"]?.debugDescription ?? "")
            }
            
            Text(doc.value["isCompleted"]?.debugDescription ?? "")
        }
    }
}
import Foundation
import OrderedCollections

class Document : Hashable, Equatable{
    static func == (lhs: Document, rhs: Document) -> Bool {
        lhs.id.description == rhs.id.description
    }
    
    let id: String
    let value: OrderedDictionary<String,Any?>
    
    init(id: String, value: OrderedDictionary<String,Any?>) {
        self.id = id
        self.value = value
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

enter image description here

0

There are 0 best solutions below