Home > Software engineering >  Value of optional type 'String?' must be unwrapped to refer to member 'lowercased
Value of optional type 'String?' must be unwrapped to refer to member 'lowercased

Time:09-07

I had a function that had no errors. Then I changed some elements in my data model to be optional. I have unwrapped these values everywhere in the code besides one part. The part I am struggling with is my filterData function.

I get the error:

Value of optional type 'String?' must be unwrapped to refer to member 'lowercased' of wrapped base type 'String'

My Data Model is:

import SwiftUI
import Foundation
import Combine

struct Product: Identifiable, Codable, Hashable {
    
    
    var id: String? = ""
    var product_name: String? = ""
  
}

My filterData function is:

func filterData(){
        
        withAnimation(.linear){
            
            self.filteredProduct = self.products.filter{
                return $0.product_name.lowercased().contains(self.search.lowercased())
            }
        }
    }

How do I safely unwrap 'product_name' in this scenario?

CodePudding user response:

By using optional chaining foo?.bar and a fallback value maybeValue ?? fallback:

func filterData() {
    withAnimation(.linear) {
        self.filteredProduct = self.products.filter {
            return $0.product_name?.lowercased().contains(self.search.lowercased()) ?? false
        }
    }
}

And slightly optimized to avoid doing the same lowercasing over and over:

func filterData() {
    withAnimation(.linear) {
        let term = self.search.lowercased()
        self.filteredProduct = self.products.filter {
            return $0.product_name?.lowercased().contains(term) ?? false
        }
    }
}
  • Related