swift 数组和结构的运行时错误

Runtime error with array and struct with swift

我是 Swift 的新手,我被困在一个一定很愚蠢的错误上!!!这是代码

import Foundation

struct Serie {
    var nomeEsercizio = ""
    var ripetizioni=0
    var chili=0.0
    var recupero=0
}

struct Superserie {
    var elementi: [Serie] = []
}

struct Scheda {
    var elementi: [Superserie] = []
}

class Schede {
    var elementi: [Scheda] = []
    func isEmpty() -> Bool {
        return elementi.isEmpty
    }
}

class GestoreDiSchede {
    static var schedeLocali = Schede()
    static var username = "empty"

class func initializeUserDefaults () {
        var superserieTemp = Superserie()
        var scheda = Scheda()
        let schede = Schede()

        superserieTemp.elementi.append(Serie(nomeEsercizio: "Spinte manubri", ripetizioni: 10, chili: 10, recupero: 0))     //....more code

我无法 post 调试器的屏幕截图,但此处结构 "superserieTemp" 中变量 "elementi" 的项目的值是随机分配的!!!!!!!为什么? 我已经尝试了所有方法,但我无法使代码正常工作,请帮忙:(

编辑 <------------ 几个小时后,我发现错误发生是因为我无法正确初始化结构数组的结构。我该怎么做? 如果我按照以下方式进行操作,那么当我尝试在更大的结构内的数组中追加一个项目时,我会收到此错误 "variable 'a' passed by reference before begin initialised"。 'a'变量指的是下面的代码。

struct Inside {
    var something: String
    var somethingElse: Int
}
struct Outside {
    var array: [Inside]
    init(){
        self.array = []
    }
}
//then the error is given in the following lines (which are placed inside a method of another class)
var a: Outside
a.array.append.(Inside("aaaa",1111))

问题出在哪里?

编辑编辑 <------------ 这是正确的(不是编译)代码,我直接在堆栈溢出中写了前一个

struct Inside {
    var something: String
    var somethingElse: Int
}
struct Outside {
    var array: [Inside]
    init(){
        self.array = []
    }
}
//then the error is given in the following lines (which are placed inside a method of another class)
        var a: Outside
        a.array.append(Inside(something: "aaaa",somethingElse: 1111))

在您的示例代码中,您没有初始化变量 a,但在 Swift 中,每个值都必须在可用之前进行初始化。将最后两行更改为:

var a = Outside()
a.array.append(Inside(something: "aaaa", somethingElse: 1111))

它对我来说很好 (Swift 2.0)

或者您可以删除阻止生成默认初始化程序的自定义初始化程序,然后它看起来像这样:

struct Inside {
    var something: String
    var somethingElse: Int
}

struct Outside {
    var array: [Inside]
}

let a = Outside(array: [Inside(something: "aaaa", somethingElse: 1111)])

您的代码存在一些错误:(1) a 未初始化。您刚刚声明它的类型为 Outside。 (2) 附加后有一个额外的点。 (3) 您需要带有 Inside.

的默认初始值设定项的参数标签
struct Inside {
    var something: String
    var somethingElse: Int
}

struct Outside {
    var array = [Inside]() // Don't need to initialize array in your init call
}

var a = Outside()
a.array.append(Inside(something: "aaaa",somethingElse: 1111))