Swift: shortcut unwrapping of array of optionals

后端 未结 7 887
孤城傲影
孤城傲影 2020-12-03 00:54

Assume we have an array of optionals defined:

var arrayOfOptionals: [String?] = [\"Seems\", \"like\", \"an\", nil, \"of\", \"optionals\"]

I

相关标签:
7条回答
  • 2020-12-03 01:39

    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 SequenceTypes that contain Optional values.

    For more information see the original answer I posted.

    0 讨论(0)
提交回复
热议问题