添加到数组时无法推断通用参数“元素" [英] Generic parameter 'Element' could not be inferred when adding to Array
问题描述
我有一个数组字典:
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]
但是,相反,我得到了错误:Generic parameter 'Element' could not be inferred
.为什么?
However, instead I get the error: Generic parameter 'Element' could not be inferred
. Why?
推荐答案
Swift 3.0
考虑简单的概念:-
Consider the simple concept :-
在单行中使用if...else
时,操作应该是单个操作,否则我们需要在parenthesis
下配对操作以使其成为单个操作,在我们的情况下,append(val)
是一个单个操作,但是myDict[key] = [val]
是多个操作(myDict[key]
是一个,并且=
分配是一个,而[val]
是1),所以我们使用parenthesis
将它们分组为单个.
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
.
以更简单的方式考虑以下arithmatic operations
.
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
在这里,我们在let a
上指示编译器不是预期的方式.
Here, we are instructing the compiler not a expected way at let a
.
也可以看到
let a:Int? = nil
var b:Int? = nil
let d = 10
let c = a ?? 10 * b ?? d
这里let c
是错误的指令,错误是
Here let c
is wrong instruction, error is,
可选类型'Int?'的值没有包装;你的意思是使用'!' 还是?"?
Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
如果我强制unwrapping
optionals a and b
,则错误将变为
If i force unwrapping
the optionals a and b
, then the error will become,
在展开可选值时意外发现nil
unexpectedly found nil while unwrapping an Optional value
所以常数c
变为
let c = a ?? 10 * (b ?? d) //100
那是您应该在default
值附近使用parenthesis
.
That's you should use parenthesis
around the default
value.
myDict[key]?.append(val) ?? (myDict[key] = [val])
这篇关于添加到数组时无法推断通用参数“元素"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!