我正在尝试使用string:int类型的字典数组。 我试图用一年的日期(作为字符串)和0(对于所有的整数)初始化该数组。
但是,我面临各种错误。编译器认为我的print语句不明确。
我的代码:
class Dates {
static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) -> [Dictionary<String, Int>] {
var details = [Dictionary<String, Int>]()
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
let sDate = fmt.string(from: startDate)
print (sDate)
details.append([sDate : 0])
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
return details
}
static func dateFromString(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: dateString)!
}
}
struct Attendee {
var masterStudentdetails = [Dictionary<String, Int>]()
init() {
masterStudentdetails = Dates.printDatesBetweenInterval(Dates.dateFromString("2018-08-22"), Dates.dateFromString("2019-08-20"))
for (dayStr, trackNum) in masterStudentdetails {
print(dayStr) //This line is causes error.
}
}
答案 0 :(得分:0)
masterStudentDetails
是一个字典数组。因此,for in
的结果为[String: Int]
,而不是键值对。
您需要迭代数组,然后迭代每个字典中的键值对。
init() {
masterStudentdetails = Dates.printDatesBetweenInterval(Dates.dateFromString("2018-08-22"), Dates.dateFromString("2019-08-20"))
for dictionary in masterStudentdetails {
for (dayStr, trackNum) in dictionary.enumerated() {
print(dayStr)
}
}
}
但由于每个字典中只有一个键值对,您可以这样做:
init() {
masterStudentdetails = Dates.printDatesBetweenInterval(Dates.dateFromString("2018-08-22"), Dates.dateFromString("2019-08-20"))
for dictionary in masterStudentdetails {
if let pair = dictionary.first {
print(pair.key)
}
}
}