Game Development Reference
In-Depth Information
If you want to both declare a variable or constant's type and initialize it at the same time,
you use this:
var color : String = "Blue"
let city : String = "Denver"
To print values to the console in Swift, you use the
print()
or
println()
function.
Their syntax is pretty straightforward. When you want to print something to the console,
you call either of these functions, passing them a
String
value. The only difference
between these two functions is that the
println()
function adds a new line after the
String
value.
Let's take a look at these functions in action. Copy the following snippet into
main.swift
and run the application:
println("Hi, I live in")
You will see output similar to this:
Hi, I live in
This is pretty simple, but notice there is no semicolon at the end of the line. Semicolons
are optional in Swift. You need them only if you put multiple statements on a single line.
Let's get back to the
print()
and
println()
functions. Your first question is prob-
ably, “How do I print the values in variables and such?” There are a couple of ways to do
this. The first is to use the
+
operator, as shown here:
var home = "Denver"
println("Hi, I live in " + home + ".")
This will print the following:
Hi, I live in Denver.
The second way to do this is to embed the variable in the
String
and surround it with
\()
.
println("Hi, I live in \(home).")
This is much simpler and will result in the same output.