Click on a topic to expand and learn in detail.
print("Hello, Swift!")
Swift is a modern, fast, and safe language used for developing Apple apps.
var age = 25 // variable
let name = "Alice" // constant
let pi: Double = 3.14 // type annotation
Use var for changeable values, let for constants.
// Arithmetic
let sum = 5 + 3
// Comparison
let isAdult = age >= 18
// Logical
let flag = isAdult && true
Operators perform calculations, comparisons, and logic operations.
if age >= 18 {
print("Adult")
} else {
print("Minor")
}
// Switch
switch age {
case 18:
print("Exactly 18")
default:
print("Other age")
}
Use if-else or switch to control program flow.
// for loop
for i in 0..<5 {
print(i)
}
// while loop
var j = 0
while j < 5 {
print(j)
j += 1
}
// repeat-while
var k = 0
repeat {
print(k)
k += 1
} while k < 5
Loops allow repeating code multiple times.
func add(a: Int, b: Int) -> Int {
return a + b
}
print(add(a: 5, b: 3))
Functions are reusable code blocks that can return values.
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func greet() {
print("Hello \(name)")
}
}
let p = Person(name: "Alice", age: 25)
p.greet()
Swift supports classes, objects, inheritance, encapsulation, and polymorphism.
// Optional Example
var name: String? = "Alice"
print(name ?? "No Name")
// Closure
let square = { (x: Int) -> Int in x * x }
print(square(5))