在我的快捷应用程序中,我具有以下功能:
func generateTimetable() -> [String:String] {
var dayCellTFText = [String]()
for i in 1...7 {
let cell = tableView.cellForRow(at: [0,i]) as! DayCell
dayCellTFText.append(cell.timetableTextField.text!)
}
let timetable = ["monday":dayCellTFText[0],"thuesday":dayCellTFText[1],"wednesday":dayCellTFText[2],"thursday":dayCellTFText[3],"friday":dayCellTFText[4],"saturday":dayCellTFText[5],"sunday":dayCellTFText[6]]
return timetable
}
当我通过例如print(generateTimetable())调用函数时 这是输出:
["thuesday": "", "wednesday": "", "saturday": "", "thursday": "", "monday": "", "friday": "", "sunday": ""]
问题在于字典的元素改变了位置! 我该怎么解决?
答案 0 :(得分:0)
对于[String : String]
的返回值,使用generateTimetable()
是错误的选择。如果要有序集合,则应使用数组。问题是数组包含的类型是什么?这是两种可能的解决方案:
一个元组:
func generateTimetable() -> [(String,String)] {
var dayCellTFText = [String]()
for i in 1...7 {
let cell = tableView.cellForRow(at: [0,i]) as! DayCell
dayCellTFText.append(cell.timetableTextField.text!)
}
let timetable = [("monday",dayCellTFText[0]),
("tuesday",dayCellTFText[1]),
("wednesday",dayCellTFText[2]),
("thursday",dayCellTFText[3]),
("friday",dayCellTFText[4]),
("saturday",dayCellTFText[5]),
("sunday",dayCellTFText[6])]
return timetable
}
一个结构
struct TableEntry {
let nameOfDay: String
let textFieldtext: String
}
func generateTimetable() -> [TableEntry] {
var dayCellTFText = [String]()
for i in 1...7 {
let cell = tableView.cellForRow(at: [0,i]) as! DayCell
dayCellTFText.append(cell.timetableTextField.text!)
}
let timetable = [ TableEntry(nameOfDay: "monday", textFieldtext: dayCellTFText[0]),
TableEntry(nameOfDay: "tuesday", textFieldtext: dayCellTFText[0]),
TableEntry(nameOfDay: "wednesday", textFieldtext: dayCellTFText[0]),
TableEntry(nameOfDay: "thursday", textFieldtext: dayCellTFText[0]),
TableEntry(nameOfDay: "friday", textFieldtext: dayCellTFText[0]),
TableEntry(nameOfDay: "saturday", textFieldtext: dayCellTFText[0]),
TableEntry(nameOfDay: "sunday", textFieldtext: dayCellTFText[0]),
TableEntry(nameOfDay: "monday", textFieldtext: dayCellTFText[0])]
return timetable
}
因此返回类型将固有地排序。如果您仍然想按字典的键对字典进行排序,则here是一个已经回答的问题。但这假设键已经具有数字或字母顺序(或与此相关的任何排序顺序)。但是字符串“ monday”,“ tuesday”,...,“ sunday”不是按字母顺序排列的。