ios - 如何获取结构中伴随的 var 值?

标签 ios swift

仍然是一个初学者,所以不确定这是否可行,但我已经解析了一个 XML 并将其保存为如下所示的结构。 XML 包含许多带有月份、事件日期和假期标签的条目。如果我检查是否有月份值,我想获取随附的事件日期和假期值。如何像这样调用结构中的其他值?

struct myEventDates {
var month = ""
var eventdate = ""
var holiday = ""
}

我有一个 Collection View 日历,一次显示一个月。每当显示的月份与保存 xml 数据的结构中的月份相同时,我想在分组的 TableView 中打印所有附带的事件日期和假期。

这是我到目前为止所做的事情。

//Mark: TableView Delegate/DataSource for Date and Holiday Names
class CalendarViewController: UITableViewDelegate, UITableViewDataSource {

 //Mark: Appended XMLParser data to this variable
 var myCalendarDatesStrut = [CalendarDates]()

//Mark: Want as many sections as there are xml entries, so checking to see if current month == month tag of entry in xml, and settings total count as numberOfSections
//This works
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    formatter.dateFormat = "MMMM"
    let currentMonthShown = formatter.string(from: selectedDate)
    let monthsFromCalendarXML = myCalendarDatesStrut.map {$0.month}
    let eventsInThisMonthCount = monthsFromCalendarXML.filter{ $0 == currentMonthShown}.count
    return eventsInThisMonthCount
}

//Mark: Want header of each section to be the entrydate. I think the way to do this is to check if month shown in calendar == month in xml entry and if so, print the eventdates as headers, but I dont know how to get the accompanying event dates

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    formatter.dateFormat = "MMMM"
    let currentMonthShown = formatter.string(from: selectedDate)
    let monthsFromCalendarXML = myCalendarDatesStrut.map {$0.month}

        if monthsFromCalendarXML.contains(currentMonthShown) {
            for each in myCalendarDatesStrut {
                print(each.eventdate, "each.eventdate") //this just prints all of the eventdates in the xml but I need it to only print the dates that have the same month.
    }}}

最佳答案

如果我理解你的意思正确,你可以先过滤数组,然后再循环它

for each in myCalendarDatesStrut.filter({ $0.month == currentMonthShown }) {
    print(each.eventdate, "\(each.eventdate)")
}

或者在循环时

for each in myCalendarDatesStrut {
    if each.month == currentMonthShown {
        print(each.eventdate, "\(each.eventdate)")
    }
}

关于ios - 如何获取结构中伴随的 var 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52527494/

相关文章:

swift - 无法快速使用递归

ios - 如何使 VStack 可点击以在 SwiftUI 中显示警报

ios - phonegap 推送通知显示 Xcode 中的错误

ios - swift4:关闭当前 View Controller 并显示另一个没有 navigationController 的 Controller

android - 使用 vue.js 和 android 的移动应用程序的区别

ios - 如何快速清除ImageView?

ios - 如何从 WKWebView 完成加载获取标题

ios - XCode 工作区中代码库的项目与目标

ios - 如何使用 if 条件执行正确的代码方法以显示何时点击 1 到 10

ios - 这是我在 Swift 中不明白的一件事