Naftali Beder
Naftali Beder

Reputation: 1076

Passing a value into a class to be used when the class is instantiated in Swift

When creating an instance of a custom class, I want to pass a value back into the class declaration, to be used when it's instantiated.

I tried doing this through a property, but that doesn't work. What is the correct way to achieve this?

(Apologies if I'm not wording the question quite right, but hopefully the code below makes my question clear.)

class hello {
    let indexInArray: Int!
    override init(frame: CGRect) {
        super.init(frame: frame)
        println("This is hello number \(indexInArray).")
    }
}

for index in 0..<4 {
    let singleHello = hello()
    singleHello.indexInArray = index
}

The desired output:

// This is hello number 0.
// This is hello number 1.
// This is hello number 2.
// This is hello number 3.

Upvotes: 0

Views: 40

Answers (2)

Schemetrical
Schemetrical

Reputation: 5536

Make a designated initialiser, such as:

init(#index: Int) {
    super.init()
    println("This is hello number \(index).")
}

and then...

for index in 0..<4 {
    let singleHello = hello(index: index)
}

So that when you initialise, you can pass in your index as a variable. If you want the frame, you can go ahead and do init(frame: CGRect, index: Int) {}

Upvotes: 0

ABakerSmith
ABakerSmith

Reputation: 22939

If I understand your question correctly, this is what you're after:

class Hello : HelloSuperClass {
    // Note - this no longer has to be declared as an implicitly unwrapped optional.
    let index: Int

    // Create a new designated initialiser that takes the frame and index as arguments.
    init(frame: CGRect, index: Int) {
        self.index = index
        super.init(frame: frame)
        println("This is hello number \(self.index).")
    }
}

for i in 0..<4 {
    let singleHello = Hello(frame: CGRect(), index: i)
}

Upvotes: 1

Related Questions