Overview
This lecture introduces the concept of interactivity in apps, focusing on using variables in Swift to manage user input and display output.
Variables in Swift
- Variables temporarily store data that can be changed and reused in Swift applications.
- The keyword
var is used to declare a variable in Swift.
- A variable declaration follows the pattern:
var + variable name + = + value.
- Swift provides built-in types such as
Int (integer) for numbers and String for text.
Declaring and Assigning Variables
- You can declare a variable without an initial value by specifying its data type (e.g.,
var color: String).
- Assigning a value later is possible if the type is stated during declaration.
- If the data type is not specified, Swift uses type inference based on the initial value.
Type Safety and Type Annotation
- Swift enforces type safety, ensuring variables only store values matching their declared types.
- Assigning a value of the wrong type (e.g., assigning an integer to a string variable) results in an error.
Displaying Variables
- Functions perform special tasks; in Swift, the
print() function displays output on the screen.
- The print function syntax is:
print(value).
- You can use the plus sign (
+) to combine strings in the print statement.
- Example:
print("Hello " + firstName) displays "Hello Michael" if firstName is "Michael".
Key Terms & Definitions
- Variable — A named container for storing data that can change during program execution.
- Type Annotation — Explicitly stating the data type of a variable during declaration.
- Type Inference — Swift's ability to determine a variable's data type from the initial value.
- Function — A reusable block of code that performs a specific task.
- print() — Swift function for displaying values on the screen.
Action Items / Next Steps
- Practice declaring variables of different types in Swift.
- Try combining variables using the
+ operator and display them using print().