Home > front end >  Unable to add values (using =) to enum as it's an optional type?
Unable to add values (using =) to enum as it's an optional type?

Time:10-07

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]

Doing

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

results in this error message "Value of optional type 'Double?' must be unwrapped to a value of type 'Double'"

so I did

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

but this results in an erroneous output. (I expect it to be total of all the qty in data = []

Note : I don't want to force unwrap it.

CodePudding user response:

You should use Dictionary Key-based subscript with default value:

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

CodePudding user response:

The ?? operator has a lower precedence than (and pretty much all other operators), so you need to use parentheses to make the expression behave as you expect it to

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

Without the parentheses, the expression evaluates like this:

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