gpt4 book ai didi

swift - 无法分配给 Swift 类型的不可变表达式

转载 作者:搜寻专家 更新时间:2023-11-01 06:32:39 25 4
gpt4 key购买 nike

我看过几个类似的 SO 问题,但没有太多帮助,

我正在尝试使用 updateDailyTimes 函数使用 timesArray 更新星期一的 availabilityTimes

availabilityTimestimesArray 示例

 var availabilityTimes = [
"Monday": [ "available" : true,
"times": [
["startTime": "9:00 am", "endTime": "1:30 pm" ],
["startTime": "2:30 pm", "endTime": "6:00 pm" ],
["startTime": "7:30 pm", "endTime": "9:00 pm" ]
]
],
"Tuesday": [ "available" : true,
"times": [
["startTime": "9:00 am", "endTime": "6:00 pm" ]
]
]
]




var timesArray = [
["startTime": "9:00 am", "endTime": "1:30 pm" ],
["startTime": "2:30 pm", "endTime": "6:00 pm" ],
["startTime": "7:30 pm", "endTime": "9:00 pm" ]
]

这是我的代码,当我调用下面的函数时,我在代码行 value 中收到一条错误消息 cannot assign to immutable expression of type [[String : String]] ["times"] as [[String : String]] = timesArray

func updateDailyTimes(day: String, timesArray: [[String:String]]){

guard var updatedTimes = self.availabilityTimes as? [String: AnyObject] else{
return
}

for (key, var value) in updatedTimes {

if key == day{
for (key1, value1) in value as! [String : AnyObject]{
if key1 as String == "times" {
value["times"] as [[String : String]] = timesArray // I get an error message in this line
}
}

}
}
}

最佳答案

根据我的评论,我指的是用于开始和结束时间的自定义结构 Times 和具有所需属性的结构 DailyTimes 以及用于更新 Times 数组:

struct Times {
let start : String
let end : String
}

struct DailyTimes {
let weekday : String
var available : Bool
var times = [Times]()

mutating func update(times : [Times]) {
self.times = times
}
}

现在创建 availableTimes 字典:

var availableTimes = ["Monday" : DailyTimes(weekday: "Monday", available: true, times: [Times(start: "9:00 am", end:"1:30 pm"),
Times(start: "2:30 pm", end:"6:00 pm"),
Times(start: "7:30 pm", end:"9:00 pm")]),
"Tuesday" : DailyTimes(weekday: "Tuesday", available: true, times: [Times(start: "9:00 am", end:"6:00 pm")])]

timesArray 数组:

let timesArray = [Times(start: "9:00 am", end:"1:30 pm"),
Times(start: "2:30 pm", end:"6:00 pm"),
Times(start: "7:30 pm", end:"9:00 pm")]

由于 MondayTimes 数组已经包含 timesArray 的值,让我们更新 Tuesday

availableTimes["Tuesday"]?.update(times:timesArray)

终于证明了

print(availableTimes["Tuesday"]?.times)

另一个改进可能是使用 DateComponents 而不是 String 来表示时间。

关于swift - 无法分配给 Swift 类型的不可变表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45105405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com