Swift: shortcut unwrapping of array of optionals

后端 未结 7 895
孤城傲影
孤城傲影 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:16

    I took @Cenny's answer and decided to make an operator out of it:

    prefix operator  {}
    
    prefix func  (array: [T?]) -> [T] {
      return array.filter{ $0 != nil }.map{ $0! }
    }
    

    I'm using it to parse an array of JSON objects and filter the ones that failed:

    static func parse(j: JSONArray) -> [Agency]? {
      return j.map { self.parse($0) }
    }
    

    Update for Swift 2+:
    Use flatMap operator and it'll only return non-nil objects

提交回复
热议问题