Norse
Norse

Reputation: 648

Initializing a variable with a function in a class

I have a class sort of like the one below. It is simplified, but it illustrates my problem. I want to initialize the "number" variable with the function "square".

class SomeClass {
    let number: Int
    func square (num: Int) -> Int {
        return num * num
    }
    init(num: Int) {
        number = square(num)
    }
}

But when i make an instance of the class. For example

let instance = SomeClass(num: 2)

it throws the error: use of 'self' in method call 'square' before all stored properties are initialized.

How can i initialize the number by using the function?

Upvotes: 1

Views: 2448

Answers (2)

user3441734
user3441734

Reputation: 17534

the only way, how to do what you want to do, is declare the number as var and initialize it with some value

class SomeClass {
    var number: Int = 0
    func square (num: Int) -> Int {
        return num * num
    }
    init(num: Int) {
        number = square(num)
    }
}

let instance = SomeClass(num: 2)
instance.number // 4

Upvotes: -2

0x416e746f6e
0x416e746f6e

Reputation: 10126

In this particular case you can use class method:

class SomeClass {
    let number: Int
    class func square (num: Int) -> Int {
        return num * num
    }
    init(num: Int) {
        number = SomeClass.square(num)
    }
}

Upvotes: 7

Related Questions