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

时间:2018-09-26 23:49:38

标签: ios swift

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

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

我有一个收藏视图日历,一次显示一个月。每当显示的月份与保存xml数据的结构中的月份相同时,我都希望在分组的表格视图中打印所有附带的事件日期和假期。

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

//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.
    }}}

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的意思,则可以在遍历数组之前先对其进行过滤

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)")
    }
}