Bachyard
Bachyard

Reputation: 25

Swift Variable Initialization via Type Instance

I want to declare some variables at the beginning of a class and have their values be modified later and elsewhere. I'd rather not assign an initial garbage value to these to keep things concise.

Can I declare variables of basic types by declaring them as instances of the type? An example of what I mean is this:

class foo() {
    var isCool = Bool()
    var someInteger = Int()

    func gotTheFunc() -> Bool {
        isCool = true
        return isCool
    }
}

The compiler lets me do this, but is it something I actually can / should do when declaring class properties like this?

Thanks!

Upvotes: 0

Views: 250

Answers (2)

vadian
vadian

Reputation: 285079

You can do that but when you declare variables with basic type initializers

var isCool = Bool()
var someInteger = Int()

the complier does this

var isCool = false
var someInteger = 0

If you want to declare variables with no value, you have to use optionals

var isCool : Bool?
var someInteger : Int?

but I would avoid optionals as much as possible.

Side note: class names should begin always with a capital letter

class Foo {}

Upvotes: 0

Wilhelm Michaelsen
Wilhelm Michaelsen

Reputation: 663

You should set the properties in an init method, then you do not have to assign a value at declaration. For example:

init(someInt: Int, isCool: Bool) {
    self.isCool = isCool
    self.someInteger = someInt
}

The self keyword is not necessary, but makes it clear which is the class's property.

Upvotes: 1

Related Questions