0

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 ;-)

2
  • 1
    If your goal is to filter self.campaigns, why don't you call filter? Is there some good reason why you cannot call it? self.campaigns = self.campaigns.filter {$0.published == 1} or whatever Commented Jan 29, 2020 at 17:07
  • It's ironic that you have mentioned the word filter in your question and you are not using it. Try what @matt said, if it still didn't work do share the Object and we will help you figure out. Commented Jan 29, 2020 at 17:12

2 Answers 2

2

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}
Sign up to request clarification or add additional context in comments.

4 Comments

this ^ map should really only be used when changing the type. compactMap is kind of like a map + filter so not preferred since the resulting type is the same in your example
There is a mutating method called removeAll(where:) on RangeReplaceableCollection exactly for that. campaigns.removeAll { $0.published != 1}
Thanks @flanker for the solution. Got so stuck with map that I didn't consider to look for other functions to solve my problem :-(
Thanks @Leo Dabus for the alternative approach!!
0

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 })

2 Comments

Your code doesn't compile because the result of compactMap is an array of Bool (and after the edit an array of Int)
Nope, compactMap is wrong anyway, it transforms the type to another. The returned type of the closure must be Campaign , It works with { $0.published == 1 ? $0 : nil} but this is a cumbersome version of filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.