swiftdebuggingprintingoutputoptional-parameters

How can I do comparison of a value Optional([:])


I am logging out (well, print()-ing) some variables, and too many times as output I have value:

Optional([:])

I want to ignore this value, so I tried

if a == Optional([:]) {
    // ignore
} else {
    print(a)
}

but this didn't work - I am immediately (prior to building and running) getting the error from XCode "Binary operator '==' cannot be applied to two '[AnyHashable : Any]?' operands" How do I detect the value Optional([:]) ?


Solution

  • The error message suggests that a is of type [AnyHashable: Any]?. This is not comparable with == because Any is not Equatable.

    Your goal is to not print anything when a is not nil and is an empty dictionary. This can be done by checking isEmpty.

    if a?.isEmpty != true {
        print(a)
    }
    

    When a is nil, a will be printed because a?.isEmpty evaluates to nil, which is not true.

    When a is not nil and is not empty, a will also be printed because isEmpty is false.

    When a is not nil and is empty, isEmpty will be true and so nothing will be done.