Bernhard Engl
Bernhard Engl

Reputation: 271

Filter out objects in an array in Swift

I've got var campaigns: [Campaign] = [] Campaign objects have a property published. I'd like to map through the array and filter out unpublished campaigns so that the result is an array holding published campaigns only I've tried below but get of course get 'nil' is incompatible with return type 'Campaign'

self.campaigns = self.campaigns.map({ (campaign) -> Campaign in
                        if campaign.published == 1 {
                            return campaign
                        } else {
                            return nil
                        }
                    })

Anyone knowing the solution to this mini-problem? Thanks ;-)

Upvotes: 0

Views: 549

Answers (2)

Mashood Murtaza
Mashood Murtaza

Reputation: 487

Agreed with @flanker answer Use compactMap that returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

self.campaigns = self.campaigns.compactMap({ $0.published == 1 ? $0 : nil })

Upvotes: 0

flanker
flanker

Reputation: 4200

To do it your way you'd need to use compactMap in order to drop the nil responses, however you'd be better off just using filter

campaigns = campaigns.filter{$0.published == 1}

Upvotes: 2

Related Questions