Beginner Codable Struct + Firebase question

Am new to Swift but as am learning I am also trying to develop my own app.

So I have a Struct that is Codable as it’s connecting to FireStore but I can’t get me head around how I add records. I have written a function called addRecord -

    func addRecord(_ event: Events) {
    do {
      let _ = try db.collection(K.FStore.eventsCollection).addDocument(from: event)
    catch {
      print("There was an error while trying to save a event \(error.localizedDescription).")

This is my Events Struct -

struct Events: Codable, Identifiable {
@DocumentID var id: String? = UUID().uuidString
var name: String
var venue: String
var description: String
var date: String
var time: String
var passcode: String
var privateEvent: Bool
@ServerTimestamp var createdTime: Timestamp?

I have a form to capture all the details but I am having trouble passing a Event to my function addRecord. So I thought create a variable called newEvent = Events, then populate it with all my fields and then call the addRecord function with newEvent. But I can’t even create the variable I get a decodable error. If I take the Codable bit of the struct I can create it.

I tried following a long with a tutorial from Peter Friese but it was far too advanced, he uses classes and code I can’t even read.

Not sure if there is enough information to be of any help. Obviously I have more code than what’s shown.



Hi @thedaveb, I’m not familiar with using Firestore and codable together so I’m not the best candidate to provide a specific answer to your question. However, I’ve provided a few resources that may provide you with some helpful information.

Video tutorial by Firebase team - Mapping Firestore documents using Swift Codable.

Firestore Coding Lab by Firebase - Doesn’t use Codable but is a straightforward Firestore tutorial.

CodableFirebase - 3rd party library helps you to use your custom types that conform to Codable protocol with Firebase.


1 Like


That last link sorted it. I noticed the error as soon as I seen the readme.

I was using -

    @State var newEvent = Events

I should of been using -

    @State var newEvent: Events

Well you learn from your mistakes.


1 Like

@thedaveb Glad you sorted it out! Cheers! :]

This topic was automatically closed after 166 days. New replies are no longer allowed.