0

This question is related to this answered question

fatal error: NSArray element failed to match the Swift Array Element type

but with an additional problem.

I'm trying to parse some JSON input and have the following two classes

class EndDiskMeridian:NSObject {
    var dispUcoefficients:Array<Double>
    var dispVcoefficients:Array<Double>
    var dispWcoefficients:Array<Double>

    init(dict: NSDictionary) {
        dispUcoefficients = dict["DispUcoefficients"] as Array<Double>
        dispVcoefficients = dict["DispVcoefficients"] as Array<Double>
        dispWcoefficients = dict["DispWcoefficients"] as Array<Double>
    }
}

class EndDisk:NSObject {
    var numberOfDivisions:Int!
    var meridians:Array<EndDiskMeridian>!

    init(dict:NSDictionary) {
        numberOfDivisions = dict["numberOfDivisions"] as Int
        meridians = dict["meridians"] as Array<EndDiskMeridian>
    }
}

The problem is when I am adding the EndDiskMeridians from the dict it is never getting to the init function in the EndDiskMeridian class.

When I go to access the dispUcoefficients I get the "fatal error nsarray element failed to match the swift array element type" error at run time.

How should I be setting up the meridians when they contain an arrays of doubles?

Community
  • 1
  • 1
Andrew
  • 521
  • 7
  • 18

1 Answers1

0

An EndDiskMeridian cannot be stored in a dictionary, so you have to construct one yourself and pass the dictionary to it.

The following code works for me in a playground:

import Foundation

class EndDiskMeridian:NSObject {
    var dispUcoefficients:Array<Double>
    var dispVcoefficients:Array<Double>
    var dispWcoefficients:Array<Double>

    init(dict: NSDictionary) {
        dispUcoefficients = dict["DispUcoefficients"] as Array<Double>
        dispVcoefficients = dict["DispVcoefficients"] as Array<Double>
        dispWcoefficients = dict["DispWcoefficients"] as Array<Double>
    }
}

class EndDisk:NSObject {
    var numberOfDivisions:Int!
    var meridians:Array<EndDiskMeridian> = []

    init(dict:NSDictionary) {
        numberOfDivisions = dict["numberOfDivisions"] as Int
        let meridians = dict["meridians"] as NSArray
        for subdict in meridians {
            let endDiskMeridian = EndDiskMeridian(dict: subdict as NSDictionary)
            self.meridians.append(endDiskMeridian)
        }
    }
}

let dict = ["EndDisk" : ["numberOfDivisions": 2, "meridians": [["DispUcoefficients": [1.0, 2.0], "DispVcoefficients": [3.0, 4.0], "DispWcoefficients": [5.0, 6.0]]]]]

let endDisk = EndDisk(dict: dict["EndDisk"]!)
Daniel T.
  • 32,821
  • 6
  • 50
  • 72