remy boys remy boys - 1 year ago 66
iOS Question

remove record from a struct according to condition

i have a

define as:

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

init(name: String, items: [String]) { = 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


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 Source

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 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download