Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. SwiftBeginner - About Variables and Constants

About Variables and Constants - Images: Japanese

Hey there, everyone! Hope you're doing well.

In the previous article, we took a deep dive into data types. If you read through that one, great work — that was a lot to cover.

Now let's move on to another topic that tends to trip up beginners: variables. Just like with data types, Swift has some pretty strict rules around variables, and you'll need to keep data types in mind as you work with them — so this is a bit trickier than in other languages. We'll push through it together. We'll also be covering constants along the way.

First things first — what exactly is a 'variable'? A variable is "a named area where you can temporarily store data, modify it, and copy it." Textbooks often use the analogy of a 'box'.

Going with that analogy: a variable is "a named box where you can temporarily store data, modify it, and copy it." The key points are that it has a name, and you can modify or copy what's inside.

That might still sound a bit abstract, so let's think back to math class. Remember equations? The ones that used 'x' and 'y'?

x + 1 = y

Variables in programming are very close to that concept. In math, you can only put numbers into those slots — but in a programming language, a variable can hold numbers, strings, booleans, and all sorts of other things.

Let's give it a try. Here's how you create a variable in Swift:

var test: String

This creates a variable called 'test' with a type of 'String'.

That might look a little mysterious. Let's break down the syntax.

First, there's 'var'. This keyword is required whenever you're creating a variable for the first time. Think of it as telling the computer, "Hey, I'm making a variable!"

Also, make sure to put a single space after var. Without it, Swift won't be able to tell where var ends and the variable name begins — and you'll get an error.

vartest: String // This causes an error.

After var, write the variable name you want to use. In this case, we're using the name test.

Then write ':' followed by the type. By the way, spaces around ':' are optional — do whatever feels comfortable.

var s: String // Spaces around ':' are optional.
var _s : String
var n:String

A variable without anything stored in it isn't very useful, so let's assign a value to it. Here's how:

var s: String
s = "Hello world" // Assign the string 'Hello world'.

There's a = with the string Hello world to its right.

One important note here: from your math experience, you might think of = as meaning "the left side equals the right side." But in programming, = is used for assignment.

And it's not left-to-right — it's right-to-left. The value on the right is assigned to the variable on the left. In programming, unless something special is going on, processing flows from right to left, so keep that in mind.

In programming, putting something into a variable (or similar) is called assignment.

One more thing to watch out for: Swift has very strict type rules. The variable s in the example above was declared as String, so it can basically only hold strings. Try to put something else in it and you'll get an error.

var s: String
s = 1 // Variable 's' was declared as String, so it can't hold a number. This is an error.

In more freewheeling languages, you can often assign anything to any variable — but not in Swift. It's a bit of a hassle, but it's worth remembering.

Alright, now that we can assign a string to a variable, let's try it out. To print the variable 's' with 'print()', the code looks like this:

var s: String
s = "Hello world" // Assign the string 'Hello world'.

print(s)

Running this gives us:

Hello world

The contents of the variable are expanded and printed correctly. When a variable holds a number, you can even do math with it directly. Check out the following code:

var n: Int // Create variables 'n' and '_n' as Int.
var _n: Int

n = 1
_n = 2

print(n + _n) // Outputs the number '3'.

Running this outputs 3. Starting to feel like real programming, right?

Also, be careful not to wrap a variable name in '"' — if you do, it becomes a string, not a variable.

var s = "Hello world"

print("s") // This is the string 's', not the variable 's' — so it outputs 's'.

Now, variables can also be overwritten. Take a look at this sample:

var s: String

s = "Hello world"
s = "Hello Swift" // Overwrite variable 's'.

print(s) // Outputs 'Hello Swift'.

We declare variable 's' as 'String', assign 'Hello world' to it, and then overwrite it with 'Hello Swift'.

Just keep in mind that when overwriting, you need to use a value of the same data type — otherwise you'll get an error. So watch out for that.

var s: String

s = "Hello world"
s = "Hello Swift" // Overwrite variable 's'. It can only hold String values.

var n: Int

n = 0
n = 1 // Overwrite variable 'n'.
n = "Hello world" // Error. Variable 'n' can only hold Int values.

So that's how overwriting works — keep it in mind.

By the way, unless something special is happening, code runs from top to bottom — so whichever assignment comes last takes effect.

var s: String

s = "Hello world"
s = "Hello Swift" // This assignment runs last.

print(s) // Outputs 'Hello Swift'.

Still with us? Good.

So far, we've been creating a variable and then assigning a value to it in a separate step. But you can also create a variable and assign a value to it at the same time, like this:

var s: String = "Hello world" // Create the variable and assign 'Hello world' at the same time.

print(s) // Outputs the string 'Hello world'.

Assigning a value to a variable at the same time it's created is called initialization. The value assigned is called the initial value.

Note that the following is NOT initialization — it's just a regular assignment:

var s: String

s = "Hello world" // This is just a regular assignment.

print(s) // Outputs the string 'Hello world'.

It's a subtle distinction, but initialization means assigning a value at the exact moment of creation — so the example above doesn't qualify.

Here's something useful: when you initialize a variable, you don't need to specify the data type.

Here's what that looks like:

var s = "Hello world" // Notice: no type specified.

print(s) // Outputs the string 'Hello world'.

Up until now we'd been writing 'variable name: data type' to specify the type. But when you initialize a variable, you can skip the type declaration — Swift will automatically figure out the appropriate data type based on the initial value.

In the example above, the initial value is the string 'Hello world', so Swift treats it as if 'String' had been specified.

var s = "Hello world" // Treated as if 'String' was specified, because 'Hello world' is a string.

print(s) // Outputs the string 'Hello world'.

Initializing with a number gives you an 'Int' variable, and so on. Here are a few examples to illustrate:

var s = "Hello world" // Initial value is a string, so it's created as 'String'.
var n = 1 // Initial value is 1, so it's created as 'Int'.
var n = 3.14 // Initial value is 3.14, so it's created as 'Double'.

In Swift, you'll often create variables using initialization, so make sure you've got this syntax down.

So far, we've been writing strings directly with '"', and writing numbers directly in the code.

This "write it directly" style of writing has a name — it's called a literal or literal expression.

A literal that writes a string is called a 'string literal'. One that writes an integer is called an 'integer literal'. And so on — each kind has its own name.

So if a colleague says "write a string literal for Hatsune Miku here," you'd write "初音ミク".

"初音ミク" // String literal.
1 // Integer literal.
3.14 // Floating-point literal.
true // Boolean literal.

A literal means "a constant written directly as a value," so anything written as a direct value in your code counts as a literal.

Note that the exact meaning of literal can vary slightly between languages, so keep that in mind.

If you only declare a variable without assigning anything, trying to access its value will cause an error.

var s: String // Just declare it.

print(s) // Error.

To avoid this, make sure to assign something.

var s: String // Just declare it.

s = "" // Assign an empty string.

print(s) // OK.

In other languages, accessing an unassigned variable often returns something like null, nil, or undefined without causing an error — but in Swift, that's not OK. Watch out for this.

A common technique is to initialize the variable with some placeholder value right from the start:

var s: String = "" // Initialize with an empty string right away.

print(s) // OK.

Now let's cover 'constants'. Constants work almost exactly like variables, with one key difference: once you assign a value, you can't overwrite it. Think of it as "a variable that can't be changed."

Constants are declared with let instead of var. The syntax is otherwise the same as with variables.

// Declare constants.
let n = 1
let _n: Int = 2
let s: String

Let's try a few things out.

First, let's try to overwrite an initialized constant:

let n = 1
n = 2 // Error.

Yep, that's an error.

What about declaring a constant without initializing it, then assigning a value afterward?

let n: Int
n = 1 // OK.

That works. But if you then try to assign again:

let n: Int
n = 1 // OK.
n = 2 // Error.

Error. Once a value has been assigned to a constant, it can't be changed. This is a common mistake, so be careful.

Other languages have constants too, but they tend to be less strict — so in practice, a lot of people just use variables for everything.

However, Swift has a concept (more or less) that says: "If a value never changes after its first assignment, it should be a constant, not a variable." So you'll often find yourself needing to think about when to use each one.

That said, Xcode will quietly let you know when a variable could be a constant — so just following Xcode's suggestions will usually get you where you need to be.

You might not see this in Playgrounds, but once you start building an actual app you'll encounter it pretty quickly.

* We'll cover this in more detail in the Xcode Beginner's Course — probably.

The names of things like variables and constants are called identifiers.

In everyday conversation you'll usually hear people say "variable name" or "constant name," but in more advanced textbooks you might see identifier instead.

Keep in mind that 'identifier' is a broader term — it refers to any name that identifies something within a set, including function names, array names, and more. It's not limited to variable and constant names.

Creating a variable is called a variable declaration. Creating a constant is called a constant declaration.

Sometimes they're referred to together as simply declarations. You'll hear "variable declaration" all the time, but "constant declaration" is used less frequently — probably because most other languages aren't as strict about the variable/constant distinction as Swift.

You might get nitpicked on some helpful feedback from a senior colleague saying "hey, this declaration looks off" — so it's worth knowing the term.

In Swift, valid characters for identifiers include letters, digits, underscores, and the dollar sign.

let n = 0
let _n = 1
let $ = 2

Digits cannot be used as the first character of an identifier — but they're fine from the second character onward. Also, half-width and full-width spaces cannot be used in identifiers.

let n1 = 0 // OK.
let 1n = 1 // Error.

let   = 2 // Full-width space. Error.

Also, using _ on its own triggers a wildcard or other special behavior — so it can't be used as a regular identifier. Similarly, combinations like '$0' (dollar sign followed by a number) are reserved for other purposes, so those are off-limits too.

let _ = 0 // You can define it, but it's not a regular constant — be careful.

print(_) // Trying to print it like this causes an error.

let $0 = 1 // This is also invalid.

Unicode characters are also supported, which means Japanese characters technically work too — just between us.

let 初音ミク = "ミクだよー" // This actually works.

print(初音ミク) // Outputs the string 'ミクだよー'.

One more thing: Swift reserved words cannot be used as identifiers.

You can technically force reserved words to work as identifiers by wrapping them in backticks (` `), but there's rarely a good reason to do that — better to just avoid it.

Swift is case-sensitive.

var n = 1 // Case-sensitive, so these are two different variables.
var N = 2

This varies a lot between languages — some are case-sensitive and some aren't — so it's a detail worth watching. Even the author trips up on this one.

Reserved words are names reserved for features that might be implemented in the language in the future. All reserved words must be blocked from use as identifiers like variable names in advance.

Here's why: imagine the language plans to add a feature called hoge in the future.

If hoge isn't already reserved, then old code that used hoge as a variable name could break when run in a newer version of the language — because hoge would now mean something different from what was originally intended.

That's why reserved words can't be used as identifiers.

If you want to look up Swift's reserved words, check the official documentation or search for "Swift reserved words" — you should find what you need.

In Swift, you can declare multiple variables or constants at once by separating them with ,.

let n = 0, s = "初音ミク", d = 3.14 // Declare multiple constants at once using ','.

This syntax is used pretty often, so it's worth memorizing.

This article got pretty long, so let's wrap it up here.

We haven't covered the practical use of variables and constants yet, so we'll get into that in the next article.

That's all for now — see you next time!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .