Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

int64

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?

like image 753
Tarps Avatar asked Jan 20 '16 14:01

Tarps


1 Answers

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
like image 82
Rob Napier Avatar answered Oct 15 '22 10:10

Rob Napier