remy boys remy boys - 21 days ago 6
iOS Question

remove record from a struct according to condition

i have a

struct
define as:

struct Section {
var name: String!
var items: [String]!

init(name: String, items: [String]) {
self.name = name
self.items = items
}
}


now how can i filter this struct according to number of items in record. say i wanna remove every record if items is nil

e.g.

sections = [
Section(name: "Mac", items: ["MacBook", "MacBook Air", "MacBook Pro", "iMac", "Mac Pro", "Mac mini", "Accessories", "OS X El Capitan"]),

Section(name: "iPad", items: []), // no Items in this record (remove this)

Section(name: "iPhone", items: ["iPhone 6s", "iPhone 6", "iPhone SE", "Accessories"]),

]


the above data have 3 records where record#2 ("iPad") dont have any items so how can i remove it from my struct ????

Answer

First of all don't declare items as implicit unwrapped optional since you are using an initializer which expects a non-optional.

The benefit is that you need to check only for emptiness rather than additionally for nil

let filteredSections = sections.filter { !$0.items.isEmpty }