3

Why is it that when I create arr, an array then try to populate it with integers using a for-in loop it, gives me an error when I don't initialize it. From what I can tell it is initialized when I write "var arr," but obviously not so what does writing var arr actually do if not initialize it.

Error Example

var arr : [Int] //Error Message: Variable 'arr' passed by reference before being initialized
for i in 1...10 {
    arr += [i]
}
arr //Error Message: Variable 'arr' used before being initialized

Working Example

var arr : [Int] = [] //Allocating memory?
for i in 1...10 {
    arr += [i]
}
arr
2
  • That is because the array was not initialized. You should initialize all the variables before use it. If you put an ! after [Int] I think you shouldn't receive that message. Commented Mar 29, 2015 at 23:33
  • I get the following error instead. '[Int]!' is not identical to 'UInt8' Commented Mar 29, 2015 at 23:37

1 Answer 1

7

Just saying var arr does not initialize your array. Should the initial value be an empty array? Should it have N copies of a given value? If it is declared to hold type A objects, should it be initialized with subtypes of A.

So you provide an initial value; the simplest is [] - an empty array.

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

4 Comments

Does that mean that not initializing your variables is a bad practice?
All variables need to be initialized either as part of their declaration or in the class's init() method. The compiler enforces this and thus it is worse than 'bad practice' it is illegal Swift.
@GoZoner All non-optional instance variables, you mean.
Right. Optionals are a special case. Thanks.

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.