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

How do I combine array sections programmatically?

与必须在 return 语句中指定每个部分相比,我如何最好地以编程方式将此传回 x 个部分?有没有一种方法可以循环并组合这些然后 return 到我的 UserSettings.Sections[x]?

的组合数组中

我当前的return声明:

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

您需要学习使用 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: [=10=]) }
}

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