Type mismatch "Int64" and "_" when trying to assign an additional Int64 to the dictionary key

Question about Swift 2.1 in Xcode 7.

I declared an optional variable as follows:

var something: Int64? 

I would like to assign it to the dictionary key later using the abbreviation if:

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

Xcode gives me the following validation error:

The result values ​​in the '?:' Expression have inappropriate types: 'Int64' and '_'

What is the problem? Why is the optional Int64 parameter not equal?

+6
source share
4 answers

There are a number of problems. Firstly, Int64 not an AnyObject . None of the primitive types of numbers are class. They can be tied to AnyObject using NSNumber , but you do not get automatic bridging for Int64 (see MartinR comment. I initially said that it was because it was wrapped in an option, but it was actually fixed -width )

Further, this syntax:

 (something != nil) ? something! : nil 

This is just a tricky way to say something .

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

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

Of course, if at all possible, get rid of AnyObject . This type is a huge pain and causes many problems. If it was [String: Int64] , you could simply:

 dictionary["something"] = something 
+7
source

You cannot add Int64 to a dictionary like [String : AnyObject] , you need to include it in an NSNumber object. You can store objects matching AnyObject in a dictionary.

 var something: Int64? something = 42 if let myVal: Int64 = something { // unwrap to make sure the value is there let myNum = NSNumber(longLong: myVal) // create an NSNumber from your Int64 dictionary["something"] = myNum // insert it into the dictionary } 

As Anton Bronnikov said below, if your dictionary was of type [String : Int64] , you could add Int64 to it without problems.

+2
source

It looks like others have already pointed out problems with the types of your dictionary. I want to add that you can also use the union operator nil '??' as an even more concise reduction of what you do in your example. This is most useful if you want to check for nil (and if not zero), expand the value and assign it, otherwise specify a default value.

 var maybeSomething: Int? var dictionary:[String:Int?] = [:] dictionary["something"] = maybeSomething ?? nil 
+1
source

something! has type Int64. Not necessarily Int64, but Int64. nil is of type nil. You cannot have an expression

 condition ? Int64 : nil 

What will be its type?

And all this is pointless. On the right side you will just have something. If this does not work, then your dictionary does not accept additional options.

PS. Noticed that your dictionary wants to store Objective-C objects. In this case, it does not accept optional. And it only accepts Int64 after converting to NSNumber.

0
source

All Articles