Listing 3.1 Big or small?


#1

Hello,
In the following sample code from the 2nd book, Xcode 10 insists of message variable to be initialised when it is declared:

import Cocoa

var population: Int = 5422

var message: String

if population < 10000 {

message = “(population) is a small town!”

} else {

message = “(population) is pretty big!”

}

print(message)

Error Message: error: Conditionals.playground:3:1: error: variables currently must have an initial value when entered at the top level of the REPL
var message: String

So, I initialise the message variable as follows before use:
var message: String = " " and the code works perfectly!


#2

I’m finding the same state here and with other variables in previous exercises. I’ve read that the variables do not need to be initialized but I cannot run the playground successfully without that. I’d love to have some clarification on the error message.


#3

Uninitialised variables are a common cause of coding errors.

The Swift Programming Language is designed to detect such errors before they cause mayhem :slight_smile:

If you have just started to learn coding, you should read Swift Programming Language.

If you want to become a real coder you can find me here to discuss how to reach that goal.


#4

I am reading and following the examples in Swift Programming 2nd Edition. I have Xcode 10 installed and am using it. What I’m finding consistently is that the examples in the book show uninitialized variables but that these variables don’t actually work. For an INT I have to create an initial state for a String I had to create a similar initial state using “” It makes me wonder if I’m doing something wrong when I work the examples but it also seems to be the only way to keep working forward in the examples. Being new at this I’m a bit concerned with what I’m learning.