0

I'm familiar with the if let .. pattern for unwrapping optionals and use this frequently to check for nil, however when dealing with dictionaries in Swift the pattern seems to break down. Can someone explain why the following does not work in Swift 4? ... The following snippet is Playground Ready!™

import UIKit

let test: Any? = nil

if let _ = test {
    print("This works as expected and does not print")
}

//let d1: [String: Any] = ["foo": "fooval", "bar": NSNull()]

let d2: [String: Any?] =  ["foo": "fooval", "bar": NSNull(), "flim": nil]


if let _ = d2["flim"] {
    print("I don't expect this to print but it does")
}

Ultimately I want to extend Dictionary so there is a null check for JSON parsing/encoding which can handle both missing values (where nil is returned from the key AFAIK) and JSON null values which I guess return NSNull (at least that what is required when encoding to get a JSON null value). Here is what I have so far

extension Dictionary  where Key == String {

    func isNullOrEmpty(key: String) -> Bool {

        // Value is NSNull instance
        if let _ = self[key] as? NSNull {
            return true
        }
        // Test if value is optional and null
        if let _ = self[key] {
            return false
        }
        // Test if key/value is missing altogether
        if self[key] == nil {
            return true
        }
        return false
    }
}
Brendan
  • 18,771
  • 17
  • 83
  • 114
  • so what is your question? – Ruslan Serebriakov Nov 28 '17 at 19:17
  • 1
    The explanation for the behaviour you are seeing is in the duplicate, but I don't think that you really want a dictionary of `String:Any?` - you just want `String:Any`. Certainly that is what you get from `NSJSONSerializer`. You then need to retrieve your desired key from the dictionary using `if let...` then check the retrieved value explicitly for `NSNull` - `if value as? NSNull != NSNull() {...` – Paulw11 Nov 28 '17 at 19:34
  • 1
    See https://gist.github.com/paulw11/fc996d00fceefd138094b5fc2e455902 – Paulw11 Nov 28 '17 at 19:40

0 Answers0