Swift is Apple modern programming language for iOS, macOS, watchOS and tvOS development. Launched in 2014, it has become one of the most loved programming languages with a clean syntax and powerful features.
Swift Basics
// Variables and constants
var name = "John" // mutable
let age = 25 // immutable (preferred)
// Type annotations
var score: Int = 0
var price: Double = 9.99
var isActive: Bool = true
var message: String = "Hello"
// String interpolation
let greeting = "Hello, \(name)! You are \(age) years old."
Optionals โ Swift Key Feature
// Optional type - may or may not have a value
var email: String? = nil
email = "user@example.com"
// Safe unwrapping with if let
if let email = email {
print("Email: \(email)")
} else {
print("No email provided")
}
// Guard statement (preferred for early returns)
func sendEmail(to recipient: String?) {
guard let email = recipient else {
print("No email address")
return
}
print("Sending to \(email)")
}
// Nil coalescing operator
let displayEmail = email ?? "Not provided"
// Optional chaining
let length = email?.count // Returns Int? not Int
Closures
// Closure syntax
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}
// Trailing closure syntax
[1, 2, 3, 4, 5].filter { $0 > 2 } // โ [3, 4, 5]
[1, 2, 3].map { $0 * 2 } // โ [2, 4, 6]
[3, 1, 2].sorted { $0 < $1 } // โ [1, 2, 3]
Structs and Classes
// Struct (value type - preferred)
struct User {
let id: String
var name: String
var email: String
var initials: String {
name.split(separator: " ")
.compactMap { $0.first }
.map { String($0) }
.joined()
}
mutating func updateName(_ newName: String) {
name = newName
}
}
// Class (reference type)
class NetworkManager {
static let shared = NetworkManager()
private init() {}
func fetchUser(id: String) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
}
SwiftUI โ Modern iOS UI
import SwiftUI
struct ContentView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 20) {
Text("Count: \(count)")
.font(.largeTitle)
.fontWeight(.bold)
HStack {
Button("โ") { count -= 1 }
.buttonStyle(.bordered)
Button("+") { count += 1 }
.buttonStyle(.borderedProminent)
}
}
.padding()
}
}
๐ Explain Swift code instantly
Paste any Swift or SwiftUI code into our AI Code Explainer for a detailed breakdown with iOS best practices.
Try AI Code Explainer โ