david david - 5 days ago 7
Swift Question

convert [Dictionary<String,Any?>] to [Dictionary<String,Any!>] ? swift 3

I am trying to append

[Dictionary<String,Any!>]
to
[Dictionary<String,Any?>]


but i am keeping 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 i am getting this error on swift3 ? why i don't get this error with swift2 ?
how to to solve the problem ?

Thanks

Answer

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.

Comments