UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.