这个问题与这个已回答的问题有关
fatal error: NSArray element failed to match the Swift Array Element type
但还有一个问题。
我正在尝试解析一些JSON输入并拥有以下两个类
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>
}
}
问题是,当我从dict添加EndDiskMeridians时,它永远不会到达EndDiskMeridian类中的init函数。
当我去访问dispUcoefficients时,我在运行时得到“致命错误nsarray元素无法匹配swift数组元素类型”错误。
当它们包含一系列双打时,我应该如何设置经络?
答案 0 :(得分:0)
EndDiskMeridian
无法存储在字典中,因此您必须自己构建一个并将字典传递给它。
以下代码适用于游乐场:
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"]!)