How can I create a static array in Swift

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I wanna create a static array in my singleton GameManager class. Aim is filling out this array with coming questions from database and reach them from other classes.

Here is Question structure:

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
    }
}

It s the singleton Class

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()
}

Answers

You should do the initialization in the constructor of the GameManager class!

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

The initializer is declared private because you obviously don t want other code to create another instance of the singleton.

Also, since a lot of the singletons like UIApplication.sharedApplication has been renamed to shared in Swift 3, you should probably rename sharedInstance to shared as well.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/40113385/how-can-i-create-a-static-array-in-swift

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils