如何以编程方式组合数组部分?

时间:2018-01-09 19:52:13

标签: ios arrays swift sections

如何以编程方式将此数字传回给x个部分而不必在return语句中指定每个部分?有没有办法循环并组合这些然后返回组合数组为我的UserSettings.Sections [x]?

我目前的回复声明:

return [self.loadFAQs(), self.loadX(section: UserSettings.Sections[0]), self.loadX(section: UserSettings.Sections[1])]

class func getZendeskFAQs() -> [ZendeskFaqs] {

    // Clear storage
    clearDataFAQs()

    let count = loadArticles(labels: UserSettings.Sections)
    print("total articles loaded: ", count)

    // the number of self.loadX sections will vary... how do I do this and return?
    return [self.loadFAQs(), self.loadX(section: UserSettings.Sections[0]), self.loadX(section: UserSettings.Sections[1])]


}

// MARK - Private methods to load data
private class func loadFAQs() -> ZendeskFaqs {
    var faqs = [ZendeskFaq]()
    faqs.append(ZendeskFaq(titled: "faq 1.1"))
    faqs.append(ZendeskFaq(titled: "faq 1.2"))
    faqs.append(ZendeskFaq(titled: "faq 1.3"))
    return ZendeskFaqs(section: "Set 1", includeFAQs: faqs)
}
private class func loadX(section: String) -> ZendeskFaqs {
    var faqs = [ZendeskFaq]()

    var myIndex = 0

    while myIndex < articleData.count {
        if section == articleData[myIndex].label_name {
            faqs.append(ZendeskFaq(titled: articleData[myIndex].title))
        }
        myIndex = myIndex + 1
    }
    return ZendeskFaqs(section: section, includeFAQs: faqs)
}

1 个答案:

答案 0 :(得分:0)

您需要学习使用Swift中可用的优美方法来收集集合,例如mapfilterflatMap。我建议阅读这些内容,至少在Xcode中提供的文档中。

试试这段代码:

class func getZendeskFAQs() -> [ZendeskFaqs] {

    // Clear storage
    clearDataFAQs()

    let count = loadArticles(labels: UserSettings.Sections)
    print("total articles loaded: ", count)

    return [self.loadFAQs()] + UserSettings.Sections.map { self.loadX(section: $0) }
}

// MARK - Private methods to load data
private class func loadFAQs() -> ZendeskFaqs {
    var faqs = [ZendeskFaq]()
    faqs.append(ZendeskFaq(titled: "faq 1.1"))
    faqs.append(ZendeskFaq(titled: "faq 1.2"))
    faqs.append(ZendeskFaq(titled: "faq 1.3"))
    return ZendeskFaqs(section: "Set 1", includeFAQs: faqs)
}

private class func loadX(section: String) -> ZendeskFaqs {
    let faqs = articleData
        .flatMap { article -> ZendeskFaq? in
            guard section == article.label_name else {
                return nil
            }
            return ZendeskFaq(titled: article.title)
        }

    return ZendeskFaqs(section: section, includeFAQs: faqs)
}

为了获取数组中的所有元素,您可以使用map函数将其从一种类型转换为另一种类型。这就是你可以将所有部分映射到ZendeskFaqs对象的方法,正如我在代码示例中所看到的那样。

顺便说一下,您也不需要使用索引计数器,就像使用myIndex一样。你可以简单地调用类似的东西:

for article in articleData {
   if section == article.label_name {
      ...
   }
}