如何在Swift中创建静态数组?

时间:2016-10-18 16:21:57

标签: arrays swift static singleton

我想在我的单例GameManager类中创建一个静态数组。目标是从数据库填写这个数组,并从其他类中获取。

这是问题结构:

struct Question{
    let levelId : Int32
    let categoryId : Int32
    let id : Int32

    let question : String
    let fieldA : String
    let fieldB : String
    let fieldC : String
    let fieldD : String
    let answer : String

    init( categoryId : Int32, levelId: Int32,id : Int32,question : String,fieldA : String,fieldB : String,fieldC : String,fieldD : String,answer : String )
    {
        self.categoryId = categoryId
        self.levelId=levelId
        self.id=id
        self.question=question
        self.fieldA=fieldA
        self.fieldB=fieldB
        self.fieldC=fieldC
        self.fieldD=fieldD
        self.answer=answer
    }
}

它是单身人士

import Foundation

class GameManager{
    var Questions = [Question]()

    var categoryID = 0
    var levelID = 0
    var i = 0
            {
            self.Questions = Questions[Question]// I create the static Question Array here, but it does not work

            self.categoryId = categoryId
            self.levelId=levelId
            self.id=id
            self.question=question
            self.fieldA=fieldA
            self.fieldB=fieldB
            self.fieldC=fieldC
            self.fieldD=fieldD
            self.answer=answer
        }

    static let sharedInstance = GameManager()
}

1 个答案:

答案 0 :(得分:0)

您应该在GameManager类的构造函数中进行初始化!

private init() {
    // do your initialization here...
}

初始化程序声明为private,因为您显然不希望其他代码创建单例的另一个实例。

此外,由于许多单身人士(例如UIApplication.sharedApplication)已在Swift 3中重命名为shared,因此您应该将sharedInstance重命名为shared