无法向枚举添加值(使用 +=),因为它是可选类型?

Unable to add values (using +=) to enum as it's an optional type?

let data = [10.0, 20.0, 30.0, 40.0, 50.0]

var bookQty = [String : Double]()
enum activityTypeEnum : String {
  case Physics = "Physics"
  case Math = "Math"
  case Science = "Science"
  case Others = "Others"
}

for i in 0..<data.count {
    print("Data[\(i)]:\(data[i])")
    bookQty["Science"] = bookQty["Science"] ?? 0 + data[i]
}

print("bookQty:\(bookQty)") // Results in bookQty:["Science": 10.0]

正在做

bookQty["Ride"] = bookQty["Science"] + data[i]

导致此错误消息“必须将可选类型 'Double?' 的值解包为 'Double' 类型的值”

我也是

bookQty["Science"] = bookQty["Science"] ?? 0 + data[i]

但这会导致错误的输出。 (我希望它是 data = []

中所有数量的总和

注意:我不想强制打开它。

?? 运算符的优先级低于 +(以及几乎所有其他运算符),因此您需要使用括号使表达式的行为符合您的预期

bookQty["Science"] = (bookQty["Science"] ?? 0) + data[i]

没有括号,表达式的计算结果如下:

bookQty["Science"] = bookQty["Science"] ?? (0 + data[i])

您应该使用默认值的基于字典键的下标:

bookQty["Science", default: 0] += data[i]