Learn Swift - 41 Code Examples & CST Typing Practice Test
Swift is a powerful, general-purpose, compiled programming language developed by Apple for iOS, macOS, watchOS, tvOS, and Linux. It emphasizes safety, performance, and modern programming practices.
View all 41 Swift code examples →
Learn SWIFT with Real Code Examples
Updated Nov 21, 2025
Explain
Swift allows developers to write fast, safe, and expressive code.
It uses type inference and optionals to minimize common programming errors.
Supports protocol-oriented, object-oriented, and functional programming paradigms.
Core Features
Memory safety and automatic reference counting (ARC)
Error handling with try/catch
Functional programming constructs (map, filter, reduce)
Powerful standard library
Interoperability with Objective-C
Basic Concepts Overview
Variables and constants: var and let
Data types: Int, Double, String, Bool, Array, Dictionary
Functions: named, closures, and higher-order functions
Control flow: if, switch, for, while, guard
Optionals: ? and ! for safe handling of nil values
Project Structure
AppDelegate.swift / SceneDelegate.swift - application lifecycle
ContentView.swift - SwiftUI main view
Models/ - data structures
Views/ - reusable UI components
Resources/ - assets, images, and storyboards
Building Workflow
Create a project in Xcode
Design UI using SwiftUI or Interface Builder
Write code in Swift files
Use simulators or physical devices to test
Debug using Xcode debugger and instruments
Difficulty Use Cases
Beginner: console programs and basic apps
Intermediate: SwiftUI views and state management
Advanced: complex apps with protocols and generics
Expert: concurrency, Combine, and performance optimization
Community: contributing to Swift packages or open-source frameworks
Comparisons
Faster and safer than Objective-C
More modern syntax and features than C/Obj-C
Optimized for Apple ecosystem
Optionals prevent null-pointer exceptions
Supports both object-oriented and functional paradigms
Versioning Timeline
2014 - Swift 1.0 released
2015 - Swift 2.0 with error handling and protocol extensions
2016 - Swift 3.0 major API redesign
2017 - Swift 4.0 with Codable and improved String handling
2025 - Swift continues evolving with Swift 6+ features
Glossary
Optional: type that can hold a value or nil
Struct: value type data container
Class: reference type object
Protocol: defines a blueprint of methods/properties
Closure: anonymous function or lambda
Installation Setup
Install Xcode on macOS for development
Command-line tools available for Swift via swift.org
Use Swift Package Manager (SPM) for dependencies
Optional IDEs: AppCode or Visual Studio Code with Swift extensions
Run code via Xcode simulator or real devices
Environment Setup
Xcode installed on macOS
Swift compiler from swift.org
Simulator or physical device for testing
Swift Package Manager for dependencies
Playgrounds for experimentation
Config Files
Package.swift - Swift Package Manager
Info.plist - app configuration
Podfile - CocoaPods dependencies
Cartfile - Carthage dependencies
project.xcodeproj / .xcworkspace - Xcode project files
Cli Commands
swift run - execute Swift program
swift build - compile Swift project
swift test - run tests
swift package init - initialize SPM package
xcodebuild - build Xcode project from CLI
Internationalization
Use NSLocalizedString for localization
Localize UI elements and resources
Support multiple locales
Adapt date, time, and number formats
SwiftGen can automate resource handling
Accessibility
Add accessibility labels and hints
Support VoiceOver navigation
Dynamic type for font sizes
High contrast and colorblind support
Test accessibility in Xcode simulator
Ui Styling
SwiftUI modifiers for declarative styling
UIKit: storyboard and programmatic UI
Dark mode support with Color and Assets
Animations with SwiftUI transitions or UIKit animations
Responsive layouts using GeometryReader or AutoLayout
State Management
SwiftUI: @State, @Binding, @ObservedObject, @EnvironmentObject
Combine for reactive streams
UserDefaults or Core Data for persistence
Protocols for delegation
Structs and classes for local state
Data Management
Use Codable for JSON serialization
Core Data for local database
Combine publishers for reactive updates
Networking with URLSession or third-party libraries
Cache data efficiently for offline support
Architecture
Compiled language with LLVM backend
Supports protocol-oriented and object-oriented programming
Memory management via ARC
Optionals and type safety for runtime safety
SwiftUI uses declarative UI components
Rendering Model
SwiftUI uses declarative view hierarchy
UIKit updates views imperatively
Swift compiles to native machine code
SwiftUI updates are driven by state changes
Efficient layout and rendering for Apple devices
Architectural Patterns
Model-View-Controller (MVC)
Model-View-ViewModel (MVVM) with SwiftUI
Protocol-oriented design
Reactive programming with Combine
Dependency injection for testable code
Real World Architectures
iOS and macOS apps using SwiftUI
Cross-platform apps via Swift on Linux
Server-side Swift with Vapor or Kitura
Reactive apps using Combine
Swift Package Manager libraries
Design Principles
Safety via optionals and type system
Performance with compiled code and ARC
Readability and modern syntax
Protocol-oriented programming
Expressive and concise code
Scalability Guide
Use modular design and frameworks
Separate concerns via MVVM or MVC
Leverage Swift Package Manager for code reuse
Adopt protocols and generics for flexibility
Optimize performance using value types
Migration Guide
Update Swift syntax for latest version
Refactor deprecated APIs
Adopt SwiftUI for modern UI development
Replace Objective-C interop with Swift equivalents
Use Combine for reactive patterns
Performance Notes
Optimize algorithms with Swift’s value types
Avoid retain cycles using weak/unowned references
Use lazy properties for expensive initializations
Minimize frequent UI updates in SwiftUI
Profile memory and CPU using Instruments
Security Notes
Use optionals to prevent nil crashes
Validate user input
Use Keychain for sensitive data storage
Follow secure networking practices with HTTPS
Apply app sandboxing for resource protection
Monitoring Analytics
Use Instruments for profiling
Xcode debugger for runtime inspection
Crashlytics or Sentry for error reporting
Monitor memory and CPU usage
Track app performance and analytics
Code Quality
Lint code with SwiftLint
Unit test with XCTest
Integration tests for app features
Code reviews and modularization
Documentation using SwiftDoc or Xcode comments
Practical Examples
Building a simple iOS calculator app
Creating a SwiftUI-based to-do list
Implementing API calls and JSON parsing
Developing a macOS menu bar app
Creating a watchOS activity tracker
Troubleshooting
Check compiler errors in Xcode
Validate optional unwrapping
Ensure correct type usage
Debug with breakpoints and print statements
Use SwiftLint for code consistency
Testing Guide
Unit testing with XCTest
UI testing in Xcode
Performance testing with Instruments
Test-driven development (TDD) workflow
Use mocks and stubs for API testing
Deployment Options
Deploy iOS apps via App Store
macOS apps via Mac App Store or notarization
Server-side Swift via Linux deployment
Distribute Swift packages via SPM
Test apps using TestFlight for beta releases
Tools Ecosystem
Xcode IDE for Apple platforms
Swift Package Manager for dependencies
CocoaPods and Carthage for library management
Playgrounds for experimentation
Instruments for profiling performance
Integrations
SwiftUI for declarative UI
Combine framework for reactive programming
UIKit for traditional UI development
Core Data for local persistence
Networking with URLSession or Alamofire
Productivity Tips
Leverage Swift Playgrounds for experimentation
Use code snippets and templates in Xcode
Follow Apple Human Interface Guidelines
Automate builds and tests with Xcode schemes
Modularize code for reuse and maintainability
Challenges
Create a SwiftUI to-do app
Build a weather app fetching API data
Develop a macOS utility app
Implement Core Data storage
Experiment with Combine reactive streams
Learning Path
Learn basic syntax and data types
Understand optionals and error handling
Explore structs, classes, and protocols
Practice SwiftUI for declarative UI
Learn Combine and concurrency for advanced patterns
Skill Improvement Plan
Week 1: Swift basics and playgrounds
Week 2: Functions, closures, and control flow
Week 3: Structs, classes, and protocols
Week 4: SwiftUI components and state management
Week 5: Networking, Combine, and advanced patterns
Interview Questions
What are optionals in Swift?
Explain value types vs reference types
What is protocol-oriented programming?
How does ARC work in Swift?
Explain SwiftUI state management
Cheat Sheet
let x = 5 - constant
var y = 10 - variable
func greet(name: String) -> String {} - function
struct MyStruct {} - define struct
if let x = optional {} - optional unwrapping
Books
Swift Programming: The Big Nerd Ranch Guide
Hacking with Swift by Paul Hudson
Swift Apprentice by Ray Wenderlich
Pro Swift by Paul Hudson
Advanced Swift by Chris Eidhof et al.
Tutorials
Swift.org tutorials
Apple Swift Playgrounds
Hacking with Swift
Ray Wenderlich Swift courses
Swift by Sundell articles
Official Docs
https://swift.org/documentation/
https://developer.apple.com/swift/
https://developer.apple.com/documentation/swiftui/
Community Links
Stack Overflow Swift tag
Reddit r/swift
Swift Forums
GitHub open-source Swift projects
Apple Developer forums
Community Support
Swift.org official documentation
Stack Overflow Swift tag
Swift Forums
Reddit r/swift
Open-source Swift packages on GitHub
Monetization
iOS apps on App Store
macOS apps on Mac App Store
Server-side Swift SaaS products
Swift libraries and frameworks
Teaching Swift courses or tutorials
Future Roadmap
Swift concurrency improvements
Expanded cross-platform support
Better SwiftUI performance
Enhanced language safety and tooling
Integration with emerging Apple frameworks
When Not To Use
Non-Apple platforms without Swift runtime
Very low-level system programming
Projects requiring extremely mature library ecosystems outside Apple
Small scripts where scripting languages suffice
Environments with strict binary size limitations
Final Summary
Swift is a modern, safe, and fast language for Apple ecosystem development.
Supports object-oriented, protocol-oriented, and functional paradigms.
Optionals and type inference reduce runtime errors.
SwiftUI enables declarative UI programming.
Can also be used for server-side development and cross-platform applications.
Faq
Is Swift only for Apple platforms?
Primarily yes, but server-side and Linux support exists.
Can Swift interoperate with Objective-C?
Yes, full interoperability exists.
What is SwiftUI?
A declarative framework for building UIs across Apple devices.
Does Swift have memory management?
Yes, via Automatic Reference Counting (ARC).
Is Swift safe for beginners?
Yes, optionals and type safety reduce common errors.
Code Sample Descriptions
Swift Concentric Circles
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
let center = CGPoint(x: size.width/2, y: size.height/2)
for r in stride(from: 20.0, through: 180.0, by: 20.0) {
let rect = CGRect(x: center.x-r, y: center.y-r, width: r*2, height: r*2)
context.stroke(Path(ellipseIn: rect), with: .color(Color(hue: r/200, saturation: 1, brightness: 1)), lineWidth: 4)
}
}
}
}
Draws colorful concentric circles using SwiftUI Canvas.
Swift Rainbow Spiral
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
var path = Path()
let center = CGPoint(x: size.width/2, y: size.height/2)
for i in 0..<720 {
let angle = Double(i) * 0.1
let radius = Double(i) * 0.3
let x = center.x + CGFloat(cos(angle) * radius)
let y = center.y + CGFloat(sin(angle) * radius)
i == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y))
}
context.stroke(path, with: .color(.red), lineWidth: 3)
}
}
}
Creates a colorful spiral using SwiftUI Canvas.
Swift Geometric Grid Patterns
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
for x in stride(from: 0.0, to: size.width, by: 40) {
for y in stride(from: 0.0, to: size.height, by: 40) {
context.stroke(Path(CGRect(x: x, y: y, width: 40, height: 40)), with: .color(.blue))
}
}
}
}
}
Draws a geometric square grid using SwiftUI Canvas.
Swift Checkerboard Variations
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
let cell: CGFloat = 40
for row in 0..<8 {
for col in 0..<8 {
let color = (row + col).isMultiple(of: 2) ? Color.orange : Color.purple
context.fill(Path(CGRect(x: CGFloat(col)*cell, y: CGFloat(row)*cell, width: cell, height: cell)), with: .color(color))
}
}
}
}
}
Generates a colorful checkerboard pattern.
Swift Random Colored Dots
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
for _ in 0..<300 {
let x = CGFloat.random(in: 0...size.width)
let y = CGFloat.random(in: 0...size.height)
let rect = CGRect(x: x, y: y, width: 6, height: 6)
context.fill(Path(ellipseIn: rect), with: .color(Color(hue: .random(in: 0...1), saturation: 1, brightness: 1)))
}
}
}
}
Scatters random colored dots across the canvas.
Swift Abstract Rectangles
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
for _ in 0..<100 {
let rect = CGRect(x: .random(in: 0...size.width), y: .random(in: 0...size.height), width: .random(in: 20...100), height: .random(in: 20...100))
context.fill(Path(rect), with: .color(Color(hue: .random(in: 0...1), saturation: 1, brightness: 1)))
}
}
}
}
Draws randomly positioned colorful rectangles.
Swift Hexagon Tessellation
import SwiftUI
struct ContentView: View {
func hexagon(at center: CGPoint, radius: CGFloat) -> Path {
var path = Path()
for i in 0..<6 {
let angle = Double(i) * .pi / 3
let point = CGPoint(x: center.x + cos(angle) * radius, y: center.y + sin(angle) * radius)
i == 0 ? path.move(to: point) : path.addLine(to: point)
}
path.closeSubpath()
return path
}
var body: some View {
Canvas { context, size in
for x in stride(from: 30.0, to: size.width, by: 60) {
for y in stride(from: 30.0, to: size.height, by: 52) {
context.stroke(hexagon(at: CGPoint(x: x, y: y), radius: 25), with: .color(.green))
}
}
}
}
}
Creates a repeating hexagon tessellation pattern.
Swift Triangular Mosaic
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
for x in stride(from: 0.0, to: size.width, by: 40) {
for y in stride(from: 0.0, to: size.height, by: 40) {
var path = Path()
path.move(to: CGPoint(x: x, y: y))
path.addLine(to: CGPoint(x: x+40, y: y))
path.addLine(to: CGPoint(x: x+20, y: y+40))
path.closeSubpath()
context.fill(path, with: .color(.cyan))
}
}
}
}
}
Draws a colorful triangular mosaic.
Swift Kaleidoscope Designs
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
let center = CGPoint(x: size.width/2, y: size.height/2)
for i in 0..<36 {
let angle = Double(i) * .pi / 18
var path = Path()
path.move(to: center)
path.addLine(to: CGPoint(x: center.x + cos(angle)*150, y: center.y + sin(angle)*150))
context.stroke(path, with: .color(.pink), lineWidth: 2)
}
}
}
}
Creates a radial kaleidoscope design using repeated lines.
Swift Symmetrical Mandalas
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
let center = CGPoint(x: size.width/2, y: size.height/2)
for i in 0..<24 {
let angle = Double(i) * .pi / 12
let x = center.x + cos(angle) * 80
let y = center.y + sin(angle) * 80
context.fill(Path(ellipseIn: CGRect(x: x-15, y: y-15, width: 30, height: 30)), with: .color(.purple))
}
}
}
}
Draws a simple symmetrical mandala using repeated circles.
Swift Lissajous Curves
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
var path = Path()
let cx = size.width/2
let cy = size.height/2
for i in stride(from: 0.0, through: Double.pi*2, by: 0.01) {
let x = cx + CGFloat(sin(3*i) * 140)
let y = cy + CGFloat(sin(4*i) * 140)
i == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y))
}
context.stroke(path, with: .color(.blue), lineWidth: 2)
}
}
}
Draws animated-style Lissajous curves using sine functions in SwiftUI Canvas.
Swift Spirograph
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
let R = 120.0
let r = 45.0
let d = 60.0
let center = CGPoint(x: size.width/2, y: size.height/2)
var path = Path()
for t in stride(from: 0.0, through: 40*Double.pi, by: 0.02) {
let x = (R-r)*cos(t)+d*cos((R-r)/r*t)
let y = (R-r)*sin(t)-d*sin((R-r)/r*t)
let p = CGPoint(x: center.x+CGFloat(x), y: center.y+CGFloat(y))
t == 0 ? path.move(to: p) : path.addLine(to: p)
}
context.stroke(path, with: .color(.red), lineWidth: 2)
}
}
}
Creates a spirograph using hypotrochoid equations.
Swift Rose Curves
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
let center = CGPoint(x: size.width/2, y: size.height/2)
var path = Path()
for t in stride(from: 0.0, through: Double.pi*8, by: 0.01) {
let r = 150*cos(5*t)
let x = center.x + CGFloat(r*cos(t))
let y = center.y + CGFloat(r*sin(t))
t == 0 ? path.move(to: CGPoint(x:x,y:y)) : path.addLine(to: CGPoint(x:x,y:y))
}
context.stroke(path, with: .color(.pink), lineWidth: 2)
}
}
}
Draws a mathematical rose curve with polar equations.
Swift Polar Flower Equations
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context, size in
let c = CGPoint(x: size.width/2, y: size.height/2)
var path = Path()
for t in stride(from:0.0,through:Double.pi*6,by:0.01){
let r = 120*sin(6*t)
let x = c.x + CGFloat(r*cos(t))
let y = c.y + CGFloat(r*sin(t))
t==0 ? path.move(to:CGPoint(x:x,y:y)) : path.addLine(to:CGPoint(x:x,y:y))
}
context.stroke(path, with:.color(.purple), lineWidth:2)
}
}
}
Generates a flower pattern using polar equations.
Swift Fibonacci Spiral
import SwiftUI
struct ContentView: View {
let nums=[20,20,40,60,100,160,260]
var body: some View {
Canvas { context,size in
var x:CGFloat=150
var y:CGFloat=150
for n in nums{
let rect=CGRect(x:x,y:y,width:CGFloat(n),height:CGFloat(n))
context.stroke(Path(ellipseIn:rect),with:.color(.orange))
x+=10;y+=10
}
}
}
}
Approximates a Fibonacci spiral using quarter-circle arcs.
Swift Golden Ratio Patterns
import SwiftUI
struct ContentView: View {
let phi=1.618
var body: some View {
Canvas { context,size in
var w:CGFloat=40
var x:CGFloat=20
for _ in 0..<8{
let h=w*CGFloat(phi)
context.stroke(Path(CGRect(x:x,y:40,width:w,height:h)),with:.color(.green))
x+=w+10
w*=0.8
}
}
}
}
Visualizes rectangles based on the golden ratio.
Swift Harmonic Wave Interference
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
var path=Path()
for x in stride(from:0.0,to:size.width,by:1){
let y=size.height/2+CGFloat(sin(x*0.05)*40+sin(x*0.08)*40)
x==0 ? path.move(to:CGPoint(x:x,y:y)) : path.addLine(to:CGPoint(x:x,y:y))
}
context.stroke(path,with:.color(.cyan),lineWidth:2)
}
}
}
Draws the interference of two sine waves.
Swift Moiré Patterns
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
for i in stride(from:0.0,to:size.width,by:8){
context.stroke(Path{p in p.move(to:CGPoint(x:i,y:0));p.addLine(to:CGPoint(x:i+20,y:size.height))},with:.color(.black))
}
}
}
}
Creates a moiré effect by overlapping line grids.
Swift Parametric Curves
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
let c=CGPoint(x:size.width/2,y:size.height/2)
var path=Path()
for t in stride(from:0.0,through:20.0,by:0.02){
let x=c.x+CGFloat(120*cos(t))
let y=c.y+CGFloat(80*sin(2*t))
t==0 ? path.move(to:CGPoint(x:x,y:y)) : path.addLine(to:CGPoint(x:x,y:y))
}
context.stroke(path,with:.color(.indigo),lineWidth:2)
}
}
}
Draws a parametric curve using trigonometric equations.
Swift Penrose-Inspired Tilings
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
for x in stride(from:40.0,to:size.width,by:60){
for y in stride(from:40.0,to:size.height,by:60){
var p=Path()
p.move(to:CGPoint(x:x,y:y-20))
p.addLine(to:CGPoint(x:x+20,y:y))
p.addLine(to:CGPoint(x:x,y:y+20))
p.addLine(to:CGPoint(x:x-20,y:y))
p.closeSubpath()
context.stroke(p,with:.color(.brown))
}
}
}
}
}
Draws a simple Penrose-inspired tiling using repeated diamond shapes.
Swift Fractal Tree
import SwiftUI
struct ContentView: View {
func branch(_ path: inout Path,_ p: CGPoint,_ len: CGFloat,_ angle: Double,_ depth: Int){
guard depth > 0 else { return }
let end = CGPoint(x: p.x + cos(angle) * len, y: p.y - sin(angle) * len)
path.move(to: p)
path.addLine(to: end)
branch(&path,end,len*0.7,angle+0.4,depth-1)
branch(&path,end,len*0.7,angle-0.4,depth-1)
}
var body: some View {
Canvas { context,size in
var path = Path()
branch(&path,CGPoint(x:size.width/2,y:size.height-20),100,.pi/2,8)
context.stroke(path,with:.color(.green),lineWidth:2)
}
}
}
Draws a recursive fractal tree using SwiftUI Canvas.
Swift Barnsley Fern
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
var x = 0.0
var y = 0.0
for _ in 0..<50000 {
let r = Double.random(in:0...1)
let nx: Double
let ny: Double
switch r {
case 0..<0.01: nx = 0; ny = 0.16*y
case 0..<0.86: nx = 0.85*x+0.04*y; ny = -0.04*x+0.85*y+1.6
case 0..<0.93: nx = 0.2*x-0.26*y; ny = 0.23*x+0.22*y+1.6
default: nx = -0.15*x+0.28*y; ny = 0.26*x+0.24*y+0.44
}
x = nx; y = ny
let p = CGRect(x: size.width/2+CGFloat(x*45), y: size.height-CGFloat(y*45), width: 1, height: 1)
context.fill(Path(p), with:.color(.green))
}
}
}
}
Generates the Barnsley fern fractal using affine transformations.
Swift Snowflake Generator
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
let c = CGPoint(x:size.width/2,y:size.height/2)
for i in 0..<12 {
let a = Double(i)*.pi/6
var p = Path()
p.move(to:c)
p.addLine(to:CGPoint(x:c.x+cos(a)*120,y:c.y+sin(a)*120))
context.stroke(p,with:.color(.cyan),lineWidth:2)
}
}
}
}
Creates a simple radial snowflake design.
Swift Growing Vines and Branches
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
var path = Path()
var p = CGPoint(x:size.width/2,y:size.height)
path.move(to:p)
for i in 0..<150 {
p.x += CGFloat.random(in:-8...8)
p.y -= 4
path.addLine(to:p)
}
context.stroke(path,with:.color(.green),lineWidth:2)
}
}
}
Simulates organically growing vine-like branches.
Swift Sunflower Seed Pattern
import SwiftUI
struct ContentView: View {
let golden = Double.pi*(3-sqrt(5.0))
var body: some View {
Canvas { context,size in
let c = CGPoint(x:size.width/2,y:size.height/2)
for i in 0..<800 {
let r = sqrt(Double(i))*5
let a = Double(i)*golden
let x = c.x + CGFloat(cos(a)*r)
let y = c.y + CGFloat(sin(a)*r)
context.fill(Path(ellipseIn:CGRect(x:x,y:y,width:4,height:4)),with:.color(.yellow))
}
}
}
}
Draws a phyllotaxis sunflower seed arrangement.
Swift Leaf Venation Patterns
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
var path = Path()
path.move(to:CGPoint(x:size.width/2,y:50))
path.addLine(to:CGPoint(x:size.width/2,y:350))
for i in stride(from:70,to:340,by:20){
path.move(to:CGPoint(x:size.width/2,y:i))
path.addLine(to:CGPoint(x:size.width/2-50,y:i-10))
path.move(to:CGPoint(x:size.width/2,y:i))
path.addLine(to:CGPoint(x:size.width/2+50,y:i-10))
}
context.stroke(path,with:.color(.green),lineWidth:2)
}
}
}
Draws a stylized leaf with vein patterns.
Swift Particle System
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
for _ in 0..<300 {
let x = CGFloat.random(in:0...size.width)
let y = CGFloat.random(in:0...size.height)
context.fill(Path(ellipseIn:CGRect(x:x,y:y,width:3,height:3)),with:.color(.white))
}
}
}
}
Creates a basic particle system with randomly positioned particles.
Swift Fireworks Simulation
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
let c = CGPoint(x:size.width/2,y:size.height/2)
for i in 0..<200 {
let a = Double(i)*.pi/100
let r = CGFloat.random(in:40...150)
let x = c.x + cos(a)*r
let y = c.y + sin(a)*r
context.fill(Path(ellipseIn:CGRect(x:x,y:y,width:4,height:4)),with:.color(.red))
}
}
}
}
Draws a radial fireworks burst using colored particles.
Swift Boids Simulation
import SwiftUI
struct ContentView: View {
var body: some View {
Canvas { context,size in
for _ in 0..<80 {
let x = CGFloat.random(in:0...size.width)
let y = CGFloat.random(in:0...size.height)
var p = Path()
p.move(to:CGPoint(x:x,y:y))
p.addLine(to:CGPoint(x:x+8,y:y+4))
p.addLine(to:CGPoint(x:x,y:y+8))
p.closeSubpath()
context.fill(p,with:.color(.blue))
}
}
}
}
Displays randomly placed boids as a starting flock simulation.
Swift Conway's Game of Life
import SwiftUI
struct ContentView: View {
let rows = 25
let cols = 25
var body: some View {
Canvas { context,size in
let cell = size.width/CGFloat(cols)
for r in 0..<rows {
for c in 0..<cols {
if Bool.random() {
context.fill(Path(CGRect(x:CGFloat(c)*cell,y:CGFloat(r)*cell,width:cell-1,height:cell-1)),with:.color(.green))
}
}
}
}
}
}
Displays a random grid representing the initial state of Conway's Game of Life.
Swift Optionals and Closures
import Foundation
struct Person {
let name: String
let age: Int
var email: String?
}
struct PersonManager {
private var people: [Person] = []
mutating func add(_ person: Person) {
people.append(person)
}
func people(matching predicate: (Person) -> Bool) -> [Person] {
people.filter(predicate)
}
mutating func updateEmail(for name: String, to newEmail: String) -> Bool {
guard let index = people.firstIndex(where: { $0.name == name }) else {
return false
}
var person = people[index]
person.email = newEmail
people[index] = person
return true
}
}
var manager = PersonManager()
manager.add(Person(name: "Alice", age: 25, email: "alice@example.com"))
manager.add(Person(name: "Bob", age: 30, email: nil))
manager.add(Person(name: "Charlie", age: 35, email: "charlie@example.com"))
manager.updateEmail(for: "Bob", to: "bob@example.com")
let adults = manager.people { $0.age >= 30 }
for person in adults {
let email = person.email ?? "No email"
print("\(person.name): \(email)")
}
Demonstrates Swift optionals, closures, structs, and collection filtering following Apple's Swift coding style.
Swift Counter
import Foundation
struct Counter {
private(set) var count = 0
mutating func increment() {
count += 1
showCount()
}
mutating func decrement() {
count -= 1
showCount()
}
func showCount() {
print("Counter: \(count)")
}
}
var counter = Counter()
counter.showCount()
counter.increment()
counter.increment()
counter.decrement()
Implements a reusable counter using a Swift struct and mutating methods.
Swift Theme Toggle
import Foundation
struct ThemeManager {
private(set) var isDarkMode = false
mutating func toggleTheme() {
isDarkMode.toggle()
showTheme()
}
func showTheme() {
let theme = isDarkMode ? "Dark" : "Light"
print("Theme: \(theme)")
}
}
var themeManager = ThemeManager()
themeManager.showTheme()
themeManager.toggleTheme()
themeManager.toggleTheme()
Demonstrates a simple theme manager using Swift structs and methods.
Swift Score Tracker
import Foundation
struct ScoreTracker {
private(set) var score = 0
mutating func increase(by points: Int) {
score += points
showScore()
}
mutating func decrease(by points: Int) {
score -= points
showScore()
}
mutating func reset() {
score = 0
showScore()
}
func showScore() {
print("Score: \(score)")
}
}
var tracker = ScoreTracker()
tracker.showScore()
tracker.increase(by: 10)
tracker.decrease(by: 5)
tracker.reset()
Tracks a player's score using encapsulated Swift methods.
Swift Optional Binding Example
import Foundation
let names: [String?] = ["Alice", nil, "Charlie", "David", nil]
func greet(_ name: String?) {
guard let name else {
print("Name not provided")
return
}
print("Hello, \(name)")
}
for name in names {
greet(name)
}
Shows how to safely unwrap optional values using guard and optional binding.
Swift Health Tracker
import Foundation
struct HealthTracker {
private(set) var health = 100
mutating func takeDamage(_ amount: Int) {
health = max(health - amount, 0)
showHealth()
}
mutating func heal(_ amount: Int) {
health = min(health + amount, 100)
showHealth()
}
func showHealth() {
print("Health: \(health)")
}
}
var tracker = HealthTracker()
tracker.showHealth()
tracker.takeDamage(20)
tracker.heal(10)
Tracks player health using a Swift struct with encapsulated methods.
Swift Level Tracker
import Foundation
struct LevelTracker {
private(set) var level = 1
mutating func advance() {
level += 1
showLevel()
}
mutating func reset() {
level = 1
showLevel()
}
func showLevel() {
print("Level: \(level)")
}
}
var tracker = LevelTracker()
tracker.showLevel()
tracker.advance()
tracker.advance()
tracker.reset()
Manages player levels using Swift methods and encapsulated state.
Swift Coin Counter
import Foundation
struct CoinCounter {
private(set) var coins = 0
mutating func collect() {
coins += 1
showCoins()
}
mutating func spend() {
guard coins > 0 else {
print("No coins available")
return
}
coins -= 1
showCoins()
}
func showCoins() {
print("Coins: \(coins)")
}
}
var counter = CoinCounter()
counter.showCoins()
counter.collect()
counter.collect()
counter.spend()
Keeps track of collected coins using Swift structs and methods.
Swift Ammo Tracker
import Foundation
struct AmmoTracker {
private let maximumAmmo = 10
private(set) var ammo = 10
mutating func shoot() {
guard ammo > 0 else {
print("Out of ammo")
return
}
ammo -= 1
showAmmo()
}
mutating func reload() {
ammo = maximumAmmo
showAmmo()
}
func showAmmo() {
print("Ammo: \(ammo)")
}
}
var tracker = AmmoTracker()
tracker.showAmmo()
tracker.shoot()
tracker.shoot()
tracker.reload()
Tracks ammunition with shooting and reloading actions following Swift conventions.
Swift Star Collector
import Foundation
struct StarCollector {
private(set) var stars = 0
mutating func collect() {
stars += 1
showStars()
}
mutating func remove() {
guard stars > 0 else {
print("No stars available")
return
}
stars -= 1
showStars()
}
func showStars() {
print("Stars: \(stars)")
}
}
var collector = StarCollector()
collector.showStars()
collector.collect()
collector.collect()
collector.remove()
Tracks collected stars using encapsulated Swift state and methods.
Swift Power-Up Timer
import Foundation
struct PowerUpTimer {
private let maximumTime = 10
private(set) var remainingTime = 10
mutating func tick() {
guard remainingTime > 0 else {
print("Power-up expired")
return
}
remainingTime -= 1
showTime()
}
mutating func reset() {
remainingTime = maximumTime
showTime()
}
func showTime() {
print("Power-Up Time: \(remainingTime)")
}
}
var timer = PowerUpTimer()
timer.showTime()
timer.tick()
timer.tick()
timer.reset()
Simulates a simple power-up timer with countdown and reset functionality.
Frequently Asked Questions about Swift
What is Swift?
Swift is a powerful, general-purpose, compiled programming language developed by Apple for iOS, macOS, watchOS, tvOS, and Linux. It emphasizes safety, performance, and modern programming practices.
What are the primary use cases for Swift?
iOS app development. macOS desktop applications. watchOS and tvOS apps. Server-side applications using Swift on Linux. Cross-platform development with SwiftUI or server frameworks
What are the strengths of Swift?
Fast and efficient compiled language. Safe programming with fewer runtime crashes. Strong Apple ecosystem support. Modern and readable syntax. Active community and evolving language features
What are the limitations of Swift?
Primarily focused on Apple platforms. Limited third-party libraries compared to older languages. Requires Xcode for full IDE support. Smaller server-side ecosystem than Node.js or Java. Frequent updates may require code adjustments
How can I practice Swift typing speed?
CodeSpeedTest offers 41+ real Swift code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.