derdida
derdida

Reputation: 14904

Swift - create Array of Objects

i have a simple Question: I just need a Array of Objects - but thats currently not working as expected. Can u help me please?

i want to create a Object of Questions. Every Question has some Properties. And the Class Questions should return an Array of Objects containing each Question.

class Questions: Array<Question> = [] {

init() {

     var images : Array<Question> = []

        for index in 1...5 {

            let myQuestion = Question(name: "maier")
            images += myQuestion

        } 

        println(images)

    }

}

class Question: NSObject {

    var name: String

    init(name: String) {

        self.name = name

    }

} 


var q = Questions()
println(q)

Upvotes: 1

Views: 7567

Answers (1)

drewag
drewag

Reputation: 94683

I am a little confused at what you are trying to do, but I think you are trying to create a class that contains a list of questions. You can't inherit from a specific generic type. Instead you should use a member variable:

class Questions {
    var images: [Question] = []

    init() {
        for index in 1...5 {
            let myQuestion = Question(name: "maier")
            images += myQuestion
        }
    }
}

Otherwise, if you are just trying to give a name to an array of Questions:

typealias Questions = [Question]

var q = Questions()
for index in 1...5 {
    let myQuestion = Question(name: "maier")
    q += myQuestion
}

Note: [Question] is shorthand for Array<Question>

Upvotes: 3

Related Questions