Search code examples
swiftenumsoptional-variables

Optional variables in API call swift


I have a variable like below

let faces: [(face: Smiley, label: UILabel)] = [
    (Smiley(icon: .worse), UILabel()),
    (Smiley(icon: .bad), UILabel()),
    (Smiley(icon: .ok), UILabel()),
    (Smiley(icon: .good), UILabel()),
    (Smiley(icon: .amazing), UILabel())
]

with

class Smiley: UIButton {

enum Icon: Int {
    case worse = -2, bad = -1, ok = 0, good = 1, amazing = 2
}

}

I want to pass faces value to an API call only if its selected so i have below code

 let selectedRating = faces
        .map({ $0.face })
        .filter({ $0.isSelected })
        .first?.icon.rawValue ?? 1 // Using default value of 1 

and selectedRating was passed to API call. But now the condition has changed u can call API even without selecting face so default value of 1 is not required. How can i pass then?

if i try with below code:-

let selectedRating = faces
         .map({ $0.face })
         .filter({ $0.isSelected })
         .first?.icon.rawValue

I get error "Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?" on passing selectedRating in API call. How can i solve this?

In the API call,

let sessionRating: Int

was declared like above and i now changed to

let sessionRating: Int?

to enable passing of

 let selectedRating = faces
          .map({ $0.face })
          .filter({ $0.isSelected })
          .first?.icon.rawValue ?? nil 

in API call. Is this a correct way?


Solution

  • try to securely unwrap your value with:

    // If there is a selected button.
    if let selectedRating = faces
        .map({ $0.face })
        .filter({ $0.isSelected })
        .first?.icon.rawValue {
    
        print(selectedRating)
    }