let current_data: [String : Any] = ["table": "tasks", "data": ["title": title_of_task, "completed_by": date_of_task]]
if (!description_of_task.isEmpty){
current_data["data"]["description"] = description_of_task
}
I get the following error:
Value of type 'Any?' has no subscripts
CodePudding user response:
As matt notes, you need to redesign current_data
. It is possible to do what you're describing, but the code is extremely ugly, complicated, and fragile because all interactions with Any
are ugly, complicated, and fragile. It seems unlikely that you mean "Any" here. Would it be reasonable for the value to be a UIViewController, or a CBPeripheral, or an array of NSTimers? If it would be a problem to pass any of those types, you don't mean "literally any type." You almost never mean that, so you should almost never use Any.
To answer the question as asked, the code would be:
if (!description_of_task.isEmpty) {
if var data = current_data["data"] as? [String: Any] {
data["description"] = description_of_task
current_data["data"] = data
}
}
Yes, that's horrible, and if there are any mistakes, it will quietly do nothing without giving you any errors.
You could, however, redesign this data type using structs:
struct Task {
var title: String
var completedBy: String
var description: String
}
struct Row {
var table: String
var data: Task
}
With that, the code is trivial:
var row = Row(table: "tasks",
data: Task(title: "title_of_task",
completedBy: "date_of_task",
description: ""))
// ...
if !descriptionOfTask.isEmpty {
row.data.description = descriptionOfTask
}