Swift: shortcut unwrapping of array of optionals

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

    The more interesting, how to unwrap an optional array of optional values. It is important to deal when we are working with JSON, because JSON can potentially contain null value for an array of something.

    Example:

    { "list": null }
    // or
    { "list": [null, "hello"] }
    
    

    To fill a Swift struct we may have a model:

    struct MyStruct: Codable {
        var list: [String?]?
    }
    

    And to avoid working with String?? as a first item we could:

    var myStruct = try! JSONDecoder.init().decode(MyStruct.self, from: json.data(using: .utf8)!)
    let firstItem: String? = s1.list?.compactMap { $0 }.first
    

    With compactMap { $0 } we can avoid

    let i2: String?? = s1.list?.first
    

    compactMap { $0 } is an equivalent of filter { $0 != nil }. map { $0! }

提交回复
热议问题