Swift for循环嵌套数组性能

时间:2016-09-19 11:57:55

标签: ios swift syntax

哪种表现更好?

选项1

var sections: [SubMenu]

var selectedItem: BeverageItem? {
    var item: BeverageItem?
    for section in sections {
        for beverage in section.beverages {
            if beverage.isSelected {
                item = beverage
                break
            }
        }
    }
    return item
}

选项2

var selectedItem: BeverageItem? {
    var item: BeverageItem?
    if let subMenuIndex = sections.index(where: { (subMenu) -> Bool in
        for beverage in subMenu.beverages {
            if beverage.isSelected {
                return true
            }
        }
        return false
    }) {
        let subMenu = sections[subMenuIndex]
        if let beverageIndex = subMenu.beverages.index(where: { (beverage) -> Bool in
            return beverage.isSelected
        }) {
            item = subMenu.beverages[beverageIndex]
        }
    }
    return item
}

如果选项1那么你在哪里使用选项2以及为什么?

1 个答案:

答案 0 :(得分:1)

对于未排序的数组,这里最简单有效的方法(结果等于你的第一个解决方案):

var sections: [SubMenu]

var selectedItem: BeverageItem? {
    for section in sections.reverse() {// remove .reverse() if you don't really need last existed section
        for beverage in section.beverages {
            if beverage.isSelected {
                return beverage
            }
        }
    }
    return nil
}