NEW: Learn to build the incredible iOS 15 Weather app today! >>

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 ) { = state
        self.submissionDate = submissionDate
        self.state = state

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


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.


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


Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS, you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Learn More

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

Reply to this topic…

You need to create an account or log in to reply.

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.