John Hubler John Hubler - 1 year ago 113
iOS Question

Array mapping no longer working in Swift 3

In Swift 2, I had the following struct setup:

struct LogInfo {
var logNumber: Int
var logID: String
var species: String
var diameter: Float
var formClass: Int
var numLogs: Float
var boardFootage: Double

static func jsonArray(array : [LogInfo]) -> [AnyObject] {

var jsonRepresentation : [String: AnyObject] {
return [
"logNumber": String(logNumber) as AnyObject,
"logID": logID as AnyObject,
"species": species as AnyObject,
"diameter": String(diameter) as AnyObject,
"formClass": String(formClass) as AnyObject,
"numLogs": String(numLogs) as AnyObject,
"boardFootage": String(boardFootage) as AnyObject

In this code, the method "jsonArray" in the middle of my code, returns this error:

"Result value of type '[String: AnyObject]' does not conform to closure result type 'AnyObject'"

As you can see from the jsonRepresentation below, the json data is going to contain an assortment of different data types.

I attempted to cast each element in the jsonRepresentation array as "AnyObject", as you can see (which xCode suggested I do in the upgrade wizard) - but I am still getting the aforementioned error with my array mapping.

Any ideas how to fix?

Answer Source

Simply changing [AnyObject] to [[String: AnyObject]] in the jsonArray method would work.

It seems that you are returning jsonRepresentation inside the map function which is [String: AnyObject] instance, and Swift 3 does not implicitly convert [String: AnyObject] to AnyObject anymore.

static func jsonArray(array : [LogInfo]) -> [[String: AnyObject]] {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download