Link Menu Expand Document

Swift Programming

Variables Series · Lesson 2

Understanding Variable Syntax Structure

Learn the exact Swift pattern for declaring variables so your code compiles and stays predictable.

Swift Programming Xcode iOS

What to focus on while watching

  • Variable declarations follow a repeatable structure in Swift.
  • The order of keywords, names, types, and values is important.
  • Small syntax mistakes can lead to compile-time errors.

Lesson Notes and Walkthrough

This lesson teaches the shape of a variable declaration in Swift. When you learn the pattern, writing code becomes faster and debugging becomes easier.

The Structure

var name: Type = value
  • var: says this value can change.
  • name: the label you use in code.
  • Type: what kind of data (for example String or Int).
  • value: the starting data.

Beginner Example

var city: String = "Austin"
var temperature: Int = 72

print("\(city) is \(temperature) degrees.")

Output: Austin is 72 degrees.

When Can You Skip the Type?

Swift can often infer the type automatically:

var city = "Austin"   // inferred as String
var temperature = 72  // inferred as Int

For beginners, writing the type explicitly can make learning clearer.

Common Syntax Errors

  1. Using : and = in the wrong places.
  2. Mismatched types, like assigning text to an Int variable.
  3. Forgetting quotation marks around strings.

You may also like

Practice: Variable Syntax

~5 min Beginner

Goal: Write valid Swift variable declarations with explicit types.

Steps

  1. Declare a name with String type.
  2. Declare a score with Int type.
  3. Print both values with a single sentence.

Expected Output

Ada has a score of 10.
Need a hint? Use var playerName: String = "Ada" and var score: Int = 10.

Code

import Foundation

var playerName: String = "Ada"
var score: Int = 10

print("\(playerName) has a score of \(score).")