API 中的可选变量调用 swift

Optional variables in API call swift

我有一个如下所示的变量

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())
]

class Smiley: UIButton {

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

}

我想将面值传递给 API 调用,只有当它被选中时,我有以下代码

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

并且 selectedRating 已传递给 API 调用。但现在情况已经改变,即使不选择面也可以调用 API,因此不需要默认值 1。那我怎么能通过呢?

如果我尝试使用以下代码:-

let selectedRating = faces
         .map({ [=15=].face })
         .filter({ [=15=].isSelected })
         .first?.icon.rawValue

我在 API 调用中传递 selectedRating 时收到错误 "Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?"。我该如何解决这个问题?

在 API 调用中,

让sessionRating: Int

如上声明,我现在改为

让sessionRating: Int?

启用

 let selectedRating = faces
          .map({ [=16=].face })
          .filter({ [=16=].isSelected })
          .first?.icon.rawValue ?? nil 

在API调用。这是正确的方法吗?

尝试通过以下方式安全地解包您的价值:

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

    print(selectedRating)
}