0

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?

j.krissa
  • 223
  • 5
  • 21
  • 1
    Possible duplicate of [Swift 2: !, ? -" Value of optional type "..." not unwrapped"](https://stackoverflow.com/questions/33587282/swift-2-value-of-optional-type-not-unwrapped) – Tamás Sengel Mar 13 '18 at 11:51

1 Answers1

1

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)
}
omaestra
  • 101
  • 1
  • 10
  • What if i didnt select any face then i cannot pass "selectedRating" like you mentioned to the API call. – j.krissa Mar 13 '18 at 12:43
  • 1
    Then you are right adding "?? nil" at the end. That way, "selectedRating" will be if no rating is selected. Just handle the value on your API call. – omaestra Mar 13 '18 at 12:50