General parameter "Element" cannot be displayed when added to an array

I have a dictionary of arrays:

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

To populate it, I'm trying to add a value to an array with the correct index. If the array does not exist, it fails and I create a new array at this index:

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

I think I should shorten this to:

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

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

+7
dictionary arrays ios swift
source share
2 answers

Swift 3.0

Consider a simple concept:

When using if...else in one line, operations must be single, otherwise we need to perform operations under parenthesis to do this as one operation, in our case append(val) is one operation, but myDict[key] = [val] multiple ( myDict[key] is one, and = is one, and [val] is one), so we group them into single ones using parenthesis .

In a simpler 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 instruct the compiler in an let a way in let a .

Also see

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

Here let c an invalid instruction, there is an error,

The value of the optional type 'Int?' does not unfold; you wanted to use '!' or '?'?

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

zero unexpectedly found while expanding optional value

So the constant c becomes,

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

That you should use parenthesis around the default value.

 myDict[key]?.append(val) ?? (myDict[key] = [val]) 
+5
source share

Better to do it:

 var array = myDict.removeValue(forKey: key) ?? [] array.append(item) myDict[key] = array 

It removes array from myDict before mutation, so array will be the only reference to the memory of the array. Since it explicitly refers, variable operations can be applied to it without the need to copy the memory of the array.

Without this, each call to myDict[key]?.append(val) causes a write-to-write operation.

+5
source share

All Articles