1. Home
  2. /
  3. Swift
  4. /
  5. Optionals and Closures

Optionals and Closures - Swift Typing CST Test

Loading…

Optionals and Closures — Swift Code

Demonstrates Swift's type safety, optionals, and closure syntax with a practical example.

import Foundation

struct Person {
	let name: String
	let age: Int
	var email: String?
}

class PersonManager {
	private var people: [Person] = []
	
	func addPerson(_ person: Person) {
		people.append(person)
	}
	
	func findPeople(matching predicate: (Person) -> Bool) -> [Person] {
		return people.filter(predicate)
	}
	
	func updateEmail(for name: String, newEmail: String) -> Bool {
		if let index = people.firstIndex(where: { $0.name == name }) {
		people[index].email = newEmail
		return true
		}
		return false
	}
}

// Usage example
let manager = PersonManager()

let people = [
	Person(name: "Alice", age: 25, email: "alice@example.com"),
	Person(name: "Bob", age: 30, email: nil),
	Person(name: "Charlie", age: 35, email: "charlie@example.com")
]

people.forEach { manager.addPerson($0) }

let adults = manager.findPeople { $0.age >= 30 }
print("Adults: \(adults.map { $0.name })")

// Optional binding
for person in adults {
	if let email = person.email {
		print("\(person.name): \(email)")
	} else {
		print("\(person.name): No email")
	}
}

Swift Language Guide

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.

Primary Use Cases

  • ▸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

Notable Features

  • ▸Strong static typing with type inference
  • ▸Optionals to handle nullability safely
  • ▸Protocol-oriented programming
  • ▸Modern syntax with closures and generics
  • ▸SwiftUI for declarative UI development

Origin & Creator

Created by Apple Inc., primarily by Chris Lattner, and first released in 2014.

Industrial Note

Swift is specialized for Apple ecosystem development, including apps for iPhone, iPad, Mac, Apple Watch, and Apple TV, but can also be used on servers and Linux platforms.

More Swift Typing Exercises

Swift Counter with ClosuresSwift Theme ToggleSwift Score TrackerSwift Optional Binding ExampleSwift Health TrackerSwift Level TrackerSwift Coin CounterSwift Ammo TrackerSwift Star CollectorSwift Power-Up Timer

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher