Welcome to Swift Syntax, your guide to understanding the foundational syntax of Apple's powerful programming language, Swift! In this lesson, we'll dive deep into Swift, covering essential concepts from the ground up. Let's get started! š
Swift is a modern, intuitive, and powerful programming language developed by Apple for iOS, macOS, watchOS, and tvOS applications. Swift's clean syntax, built-in safety features, and strong community make it an ideal choice for beginners and seasoned developers alike.
Variables and constants allow us to store data in our Swift programs. The difference between the two lies in the ability to change the value of a variable, while a constant's value remains fixed once it's assigned.
var name: String = "John Doe"
name = "Jane Doe" // Changing the value of a variablelet pi: Double = 3.14159
// pi cannot be changed, it's a constantš Note: Always give a meaningful name to your variables and constants.
Swift supports several data types, including:
We'll explore each of these data types in detail as we progress through the lesson.
Control structures allow us to control the flow of our code. Swift includes conditional statements (if, switch), loops (for, while, repeat-while), and decision-making statements (switch).
if condition {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}Example:
let age = 25
if age >= 18 {
print("You are an adult.")
} else {
print("You are a minor.")
}for index in 1...5 {
print("Index: \(index)")
}var i = 1
while i <= 5 {
print("Index: \(i)")
i += 1
}
var j = 5
repeat {
print("Index: \(j)")
j -= 1
} while j >= 1Functions allow us to organize our code and reuse functionality. Swift supports both built-in and custom functions.
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "John Doe") // Output: Hello, John Doe!func addNumbers(a: Int, b: Int) -> Int {
return a + b
}
let sum = addNumbers(a: 3, b: 4) // Output: 7What's the difference between a variable and a constant in Swift?
In this lesson, we've covered the basics of Swift syntax, including variables and constants, data types, control structures, and functions. By mastering these concepts, you're well on your way to building amazing iOS, macOS, watchOS, and tvOS applications.
In the next lessons, we'll delve deeper into Swift, exploring advanced topics such as Optionals, Closures, Protocols, and more. Happy coding! š