0

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I know that, but what if I don't want the properties to have initial values at all?
0

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 {}

1 Comment

Oh, okay. So Swift does have default values for basic types. As far as readability goes, it seems like that's a much nicer and more concise way to declare properties. Unless I need to initialize those variables with a certain value it's okay to just let the compiler do the initialization for you.

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.