0

I'm working on a Dictionary extension that seems to be doing some odd things. The below playground replicates the issue I'm seeing. If you start a new playground in XCode, you should be able to just paste this in and see the output and the issue. When checking the self[key] != nil it comes back true for Optional(nil), but seemingly should not. So, when it checks "things" I'd think the check would fail, thus skipping adding it to newDict, but it does not.

//: Playground - noun: a place where people can play

import UIKit
import Foundation

extension Dictionary {

    //Sanitizes the current dictionary for json serialization
    //Removes nil values entirely. Makes optionals non-optional
    func jsonSanitize() -> Dictionary<Key,Value> {
        var newDict:[Key:Value] = [:]
        for key in self.keys {
            print(self[key])
            print(self[key] != nil)
            if self[key] != nil {
                print("Adding it")
                newDict.updateValue(self[key]!, forKey: key)
            }
        }
        return newDict
    }

}

var youGood = false

var dict:[String:Any] = [
    "stuff":"THINGIES",
    "things":
        youGood ?
            "WOHOO!" :
            nil as String?
]
var dict2 = dict.jsonSanitize()
steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • `Optional(nil)` == `Optional.some(nil)`, not `Optional.none` (aka `nil`) – you're working with double wrapped optionals here. Therefore comparing `self[key]` to `nil` is only going to tell you if a given value exists for a key, not whether that value itself is an optional, and if so, `nil`. Although that all being said, what exactly is your question? Is it why is your code behaving in this way, or is it to how to strip `nil` values from dictionaries? – Hamish Oct 25 '16 at 21:22
  • @Hamish That makes sense with what I'm seeing then. I'm trying to get that sanitization to strip the nils out and eliminate optionals. In the end, this dictionary goes into JSON serialization, which cannot handle types like String? or nils – steventnorris Oct 25 '16 at 21:39
  • Related (possible dupe?): [Checking for nil Value in Swift Dictionary Extension](http://stackoverflow.com/q/36018238/2976878) – Hamish Oct 25 '16 at 21:50

0 Answers0