TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Fix an Identifiable struct

Forums > Swift

I’m trying to make a struct Identifiable that defines an API JSON data. When Swift 5.5 runs the struct with the id:String! optional, it becomes id:(String!)nil, and prints “Fatal error: Unexpectedly found nil while unwrapping an Optional value.” It seems to add nil when the optional is unwrapped. Can someone point me to a tutorial or explain why this is happening and how to fix the problem?

Define JSON Data:
struct Resource: Codable, Identifiable {
    let id:String?
    let submissionDate: String?
    var state: String?
  }

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case submissionDate = "submission_date"
        case state = "state"
}

 init( submissionDate: String, state: String,  confCases: String, newCase: String, totDeath: String, confDeath: String, newDeath: String, createdAt: String ) {
      self.id = state
        self.submissionDate = submissionDate
        self.state = state
}
}

Code:
  var filteredResources: [Resource] {
        if searchText.count == 0 {
            return resources
        } else {
            return resources.filter { $0 .id! .lowercased().contains(searchText.lowercased())
            }
        }

3      

All this suggests to me is that there must be some instance of one of these where the id (and therefore the state) members are both nil.

From a design perspective, I'd say it's a bad idea to let the id member of an Identifiable be optional, since the one guarantee that the Identifiable protocol provides is that there will be an id.

4      

Thanks, I changed id to not be an optional and have id point to state , that works.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.