codingbear
codingbear

Reputation: 316

How to call instance method inside class using Swift

I am having an issue with calling an instance method within the class itself. If someone can provide me some insight it would be greatly appreciated. My current code looks like this:

class Rect
{
func printthis() -> String {
    return "this is working or what"
}

var toPrint:String = self.printthis()

}

The error I am getting in Xcode is: Use of unresolved identifier 'self'.

What am I missing here?

Upvotes: 1

Views: 3844

Answers (3)

fqdn
fqdn

Reputation: 2843

An instance of a class is not initialized and able to be referenced (even as 'self') until all of its variables have been assigned values.

An option that may work for you is to declare your variable as an implicitly-unwrapped optional, which is assigned nil by default. Then in the class's init method, since all of the variables have been assigned values, you are able to start calling methods on your instance.

class Rect {
    var toPrint: String!

    init() {
        toPrint = printthis()
    }

    printthis() -> String {
        return "this will work"
    }
}

Upvotes: 2

Alex Wayne
Alex Wayne

Reputation: 187074

You can't call an instance method without an instance. The class is merely the template for instances. So i don't what you are trying to do here...

But the answer is no, you cannot call an instance method form the class definition because there is no instance yet.


Perhaps you want to delcare a class method and use that to set an instance variable on creation? If so, you might do that like this:

class Rect {
    class func printthis() -> String {
        return "this is working or what"
    }

    var toPrint:String

    init() {
        toPrint = Rect.printthis()
    }
}

var r = Rect()
println(r.toPrint) //-> this is working or what

Upvotes: 4

Christian Dietrich
Christian Dietrich

Reputation: 11868

the problem is that swift is strict about initing all properties. you may as a workaround

class Rect
{
    func printthis() -> String {
        return "this is working or what"
    }

    var toPrint:String = ""

    init() {
        toPrint = printthis()
    }

}

Upvotes: 2

Related Questions