使用另一个不同类型的数组过滤对象数组

时间:2016-11-29 20:35:35

标签: ios arrays swift3

我已经阅读了所有我能做到的事情,但似乎无法解决这个问题。我有一个ItemManager类,它创建一个[Item]数组。我需要能够使用另一个数组[Category.name]过滤[ItemManager.Items]数组。具体来说,我想过滤ItemManager.Items中包含Category.name中的Array元素的所有Array元素。任何帮助表示赞赏。

class Item: NSObject {
    var name: String?
    var category: String?
    var price: Int?

    init(name: String, category: String, price: Int) {
        self.name = name
        self.category = category
        self.price = price
    }
}

class ItemManager: NSObject {
    static var items = [Item]()

    class func addItem(name: String, category: String, price: Int) {
        let i = Item(name: name, category: category, price: price)
        return items.append(i)
    }
}

struct Category {
    var name: [String]

    subscript(index: Int) -> String {
    return name[index]
    }
}

1 个答案:

答案 0 :(得分:0)

尝试以下内容

<强> 1。将项目添加到列表中:

ItemManager.addItem(name: "Basketball", category: "Sports", price: 20)
ItemManager.addItem(name: "Football", category: "Sports", price: 15)
ItemManager.addItem(name: "Flashlight", category: "Outdoors", price: 35)
ItemManager.addItem(name: "Code Complete", category: "Books", price: 70)
ItemManager.addItem(name: "Code Complete 2nd Edition", category: "Books", price: 72)

<强> 2。创建一个类别数组,用于过滤ItemManager.list

let categoriesToFilterBy = ["Sports", "Outdoors"]

第3。使用ItemManager.list方法过滤filter

var filteredList = ItemManager.items.filter {
    if let category = $0.category {
        return categoriesToFilterBy.contains(category)
    }
    return false
}

<强> 4。打印结果:

for item in filteredList {
    if let name = item.name, let category = item.category, let price = item.price {
        print("Item Name: \(name), Category: \(category), Price: \(price)")
    }
}

<强> 5。结果(注意:仅打印等于“体育”和“户外”的类别):

Item Name: Basketball, Category: Sports, Price: 20
Item Name: Football, Category: Sports, Price: 15
Item Name: Flashlight, Category: Outdoors, Price: 35

如果元素应该包含在返回的数组中,则数组上的filter方法将获取一个闭包,预期返回true,如果该元素不应该包含false返回的数组的一部分。

您可以在此处详细了解过滤方法:https://developer.apple.com/reference/swift/array/1688383-filter