Не удается инициализировать Struct в расширении - PullRequest
0 голосов
/ 15 апреля 2020

Я пытаюсь инициализировать свою структуру NewPost в расширении, но не могу этого сделать. Я не вижу никаких очевидных ошибок / проблем с кодом. Когда я пишу self.init ( Xcode не тянет структуру, как я ожидал) Кто-нибудь может помочь?

import Foundation

protocol DocumentSerialisable {
    init?(dictionary:[String:Any])
}

struct NewPost {
    var caption : String
    var username : String
    var location : String
    var timestamp : Date

    var dictionary:[String:Any] {
        return [
            "caption" : caption,
            "username" : username,
            "location" : location,
            "timestamp" : timestamp
        ]
    }
}

extension NewPost: DocumentSerialisable {
    init?(dictionary: [String : Any]) {
        guard let caption = dictionary["caption"] as? String,
            let username = dictionary["username"] as? String,
            let location = dictionary["location"] as? String,
            let timestamp = dictionary["timestamp"] as? Date else {return nil}

        //this were i cannot perform the following:  self.init(caption: ..., username: ..., location: ..., timestamp: ...)

    }
}

1 Ответ

0 голосов
/ 15 апреля 2020
struct NewPost: Codable {

    var username: String

    private enum CodingKeys : String, CodingKey {

        case username = "Username"

    }
//
    init(username: String) {
        self.username = username

    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        username = try container.decode(String.self, forKey: .username)

    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(username, forKey: .username)


    }

}

использование

let nP = NewPost( username: "aa")


db.collection("sampleCollectionName").document("sampleDocumentName").setData(from: nP) { err in
            if let err = err {
                print("Error writing document: \(err)")
            } else {
                print("Document successfully written!")
            }
        }

, если это не работает, покажите еще немного кода

...