簡體   English   中英

Swift中的可解碼文檔參考

[英]Decodable DocumentReference in Swift

I have a custom model in swift and it has a property of type DocumentReference I'm getting some data from a cloud function and then I'm trying to decode it back to my model.

DocumentReference本身不符合 Decodable ,因此我正在嘗試為其編寫擴展。

我無法使它工作,因為我不斷收到此錯誤:

初始化程序要求“init(from:)”只能由非最終 class“DocumentReference”定義中的“必需”初始化程序滿足

知道如何進行這項工作嗎?

我的擴展:

import Firebase

extension DocumentReference: Decodable {
    public convenience init(from decoder: Decoder) throws {
        //
    }
}

現有 model:

struct Notification: Identifiable, CollectionProtocol, DocumentProtocol {
    var id = UUID()

    var documentReference: DocumentReference
    var receiverID: String
    var type: String
    var createdAt: Date
    var requestReference: DocumentReference?
    var request: Request?

    init(document: DocumentSnapshot) {
        self.documentReference = document.reference
        self.requestReference = document["requestReference"] as? DocumentReference ?? Firestore.firestore().document("")
        self.receiverID = document["receiverID"] as? String ?? ""
        self.type = document["type"] as? String ?? ""
        self.createdAt = (document["createdAt"] as? Timestamp)?.dateValue() ?? Date()
    }
}
NS_SWIFT_NAME(DocumentReference)
@interface FIRDocumentReference : NSObject

/** :nodoc: */
- (instancetype)init
    __attribute__((unavailable("FIRDocumentReference cannot be created directly.")));

DocumentReference ( FIRDocumentReference ) 不能直接實例化; 它沒有可用的初始化程序。 要實現所需的 init,您必須在 class 本身的聲明中執行此操作。

如果您想方便地從 Firestore 數據實例化自定義對象,請考慮使用[String: Any]參數的可失敗初始化程序。 如果您只想對引用本身進行編碼/解碼,請考慮對位置本身的String值(集合和文檔名稱)進行編碼/解碼,然后使用它來重建DocumentReference

class DocumentReference 不是最終的,這意味着它可能是子分類但沒有符合 Codable 的子 class。 因此,如果您的擴展程序中的init(from decoder: Decoder)被調用,這將留給未知的 state。

一種解決方法可能是使用自己的init(from decoder: Decoder)創建一個包裝器結構,然后在那里對 DocumentReference 進行解碼。

例子:

struct Wrapped: Decodable {
    let docRef: DocumentReference

    public init(from decoder: Decoder) throws {
        let container = try decoder....

        // add the decoding code here for DocumentReference
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM