Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic parameter 'Element' could not be inferred when adding to Array

I have a dictionary of arrays:

var myDict : [String:[SomeObj]] = [:]

To populate it, I try to add a value to the array at the correct index. If the array does not exist, it fails and I make a new array at that index:

if myDict[key]?.append(val) == nil {
    myDict[key] = [val]
}

I think I should be able to shorten this to:

myDict[key]?.append(val) ?? myDict[key] = [val]

However, instead I get the error: Generic parameter 'Element' could not be inferred. Why?

like image 906
GoldenJoe Avatar asked Jul 03 '17 03:07

GoldenJoe


1 Answers

Swift 3.0

Consider the simple concept :-

While using if...else in single line the operations should be single or else we need to mate operations under parenthesis to make it as a single operation, in our case append(val) is a single operation but myDict[key] = [val] is multiple (myDict[key] is one and = assignment is one and [val] is one ) so we are grouping them into single using parenthesis.

At more simple way consider the following arithmatic operations.

//I need 10-5 = 5
let a = 2*4+2-4-3*5
print(a) // -9
//so we can seprate by ()
let b = ((2*4)+2)-(4-3)*5
print(b) //5

Here, we are instructing the compiler not a expected way at let a.

Also see,

let a:Int? = nil
var b:Int? = nil
let d = 10

let c = a ?? 10 * b ?? d

Here let c is wrong instruction, error is,

Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?

If i force unwrapping the optionals a and b, then the error will become,

unexpectedly found nil while unwrapping an Optional value

So the constant c becomes,

let c = a ?? 10 * (b ?? d) //100

That's you should use parenthesis around the default value.

myDict[key]?.append(val) ?? (myDict[key] = [val])
like image 197
Rajamohan S Avatar answered Sep 28 '22 22:09

Rajamohan S