Assume we have an array of optionals defined:
var arrayOfOptionals: [String?] = [\"Seems\", \"like\", \"an\", nil, \"of\", \"optionals\"]
I
Although you can use flatMap { $0 }
to remove nils, flatMap is actually a much more powerful function, and has an overloaded version which does something completely different (e.g. flatten [[Int]]
to [Int]
). If you're not careful, you may accidentally invoke the wrong function.
I would recommend using an extension on SequenceType to remove nils. If you use removeNils(), you'll be able to essentially do the following:
[1, nil, 2].removeNils() == [1, 2]
It works by making Optional
conform to an OptionalType
protocol which allows extending SequenceType
s that contain Optional
values.
For more information see the original answer I posted.