I am trying to append [Dictionary<String,Any!>] to [Dictionary<String,Any?>]
but I keep getting this Error:
Cannot Convert value of Type [Dictionary] to expected argument type of [Dictionary]
Although I didn't get this compile error with swift2 .
Here is my code:
class A{
var statistics = [Dictionary<String,Any!>]();
func1(){
let oldStatiscs = self.func2()
//i am getting the error here.
self.statistics.append(oldStatiscs)
}
func2 () -> [Dictionary<String,Any?>]{
}
}
Why am I getting this error on swift3? Why don't I get this error with swift2? How can this problem be solved?
Thanks
First off, even if you change both arrays of dictionaries to [Dictionary<String,Any>] you still get a similar error. You are trying to append an array to an array. So you first need to change:
self.statistics.append(oldStatiscs)
to:
self.statistics.append(contentsOf: oldStatiscs)
But even with that change, you can't append an array of [Dictionary<String,Any?>] to an array of [Dictionary<String,Any!>].
The simplest solution is to change the [Dictionary<String,Any!>] array to an [Dictionary<String,Any?>] array.
Then you end up with the following working code:
class A {
var statistics = [Dictionary<String,Any?>]();
func f1() {
let oldStatiscs = self.f2()
statistics.append(contentsOf: oldStatiscs)
}
func f2() -> [Dictionary<String,Any?>] {
return [["Hi":"There"]]
}
}
Even better is to get rid of Any? and use Any.
class A {
var statistics = [Dictionary<String,Any>]();
func f1() {
let oldStatiscs = self.f2()
statistics.append(contentsOf: oldStatiscs)
}
func f2() -> [Dictionary<String,Any>] {
return [["Hi":"There"]]
}
}
You need to explain why you think you can't change Any? to Any.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With