Search code examples
iosswiftint64

Mismatching types 'Int64' and '_' when trying to assign optional Int64 to a dictionary key


Question regarding Swift 2.1 in Xcode 7.

I have declared an optional variable like this:

var something: Int64?

I would like to later assign it to a dictionary key using a shorthand if, like this:

dictionary['something'] = (something != nil) ? something! : nil

XCode is giving me the following validation error:

Result values in '? :' expression have mismatching types: 'Int64' and '_'

What is the issue here? Why can't optional Int64 be nil?


Solution

  • There are a number of problems here. First, Int64 isn't an AnyObject. None of the primitive number types are classes. They can be bridged to AnyObject using NSNumber, but you don't get that bridging automatically for Int64 (see MartinR's comment. I originally said this was because it was wrapped in an Optional, but it's actually because it's fixed-width).

    Next, this syntax:

    (something != nil) ? something! : nil
    

    Is just a very complicated way to say something.

    The tool you want is map so that you can take your optional and convert it to a NSNumber if it exists.

    dictionary["something"] = something.map(NSNumber.init)
    

    Of course, if at all possible, get rid of the AnyObject. That type is a huge pain and causes a lot of problems. If this were a [String: Int64] you could just:

    dictionary["something"] = something