Welcome to Swift! This tutorial is designed to guide you through your first Swift program. Whether you're a beginner or an intermediate learner, we'll walk you through the steps, explaining concepts from the ground up.
Swift is a modern, powerful, and intuitive programming language for iOS, macOS, watchOS, and tvOS. It was developed by Apple for building applications across its platforms.
Before we dive into writing code, let's set up your development environment:
Install Xcode: Xcode is the Integrated Development Environment (IDE) for Swift, available on the Mac App Store.
Launch Xcode: Once installed, open Xcode from your Applications folder.
Now that Xcode is set up, let's write your first Swift program!
Swift programs are written in files with the extension .swift. Create a new Swift file by clicking File > New > File > Swift File in the Xcode menu. Name it HelloWorld.
Now, replace the content in the file with the following code:
print("Hello, World!")This code tells Swift to print the text "Hello, World!" to the console.
To run your program, click the Run button (the triangle icon) in the top left corner of the Xcode interface. A new window will open, displaying the output "Hello, World!".
What is the output of the following Swift code?
In Swift, you can store data in variables and constants. Variables can change their values, while constants cannot.
To create a variable, you need to specify its type and give it a name. Swift infers the type automatically, so we'll start with an Int (integer) variable:
var myNumber: Int = 10In this example, myNumber is the variable name, and 10 is its initial value.
To create a constant, use the let keyword instead of var:
let pi: Double = 3.14159Now, pi is a constant with the value 3.14159.
You can access the value of a variable using its name:
print(myNumber) // Output: 10To change the value of a variable, simply assign a new value:
myNumber = 20
print(myNumber) // Output: 20What is the output of the following Swift code?
Functions are reusable blocks of code that perform a specific task. Let's create a simple function that adds two numbers:
func addNumbers(num1: Int, num2: Int) -> Int {
let sum = num1 + num2
return sum
}In this function, num1 and num2 are the parameters, and sum is a local variable. The -> Int part indicates that the function returns an Int (integer) value.
To call a function, use its name followed by parentheses containing the arguments:
let result = addNumbers(num1: 5, num2: 7)
print(result) // Output: 12In this example, we call the addNumbers function with arguments 5 and 7, and the result (12) is stored in the variable result.
What is the output of the following Swift code?
That's it for our First Swift Program tutorial! You've learned about Swift, setting up your development environment, writing your first Swift program, variables and constants, and functions. Happy coding! 🎉