1

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?

2 Answers 2

7

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.