Swift Examples

Swift syntax highlighting

Swift Code Example

// Swift - Apple's powerful and intuitive programming language // MARK: - Basic Swift Features // Variables and Constants let name = "Swift" var version = 5.9 let isAwesome = true // Optional values var optionalValue: String? = nil let unwrappedValue = optionalValue ?? "default" // MARK: - Functions and Closures // Function with parameters and return type func greet(name: String) -> String { return "Hello, \(name)!" } // Function with multiple return values func minMax(array: [Int]) -> (min: Int, max: Int)? { guard let first = array.first else { return nil } var currentMin = first var currentMax = first for value in array { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } // Closure example let numbers = [1, 2, 3, 4, 5] let squared = numbers.map { $0 * $0 } // MARK: - Classes and Structures // Protocol definition protocol Drawable { func draw() } // Class with inheritance class Shape: Drawable { var name: String init(name: String) { self.name = name } func draw() { print("Drawing \(name)") } } // Struct (value type) struct Point { var x: Double var y: Double mutating func moveBy(x deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } // MARK: - Enumerations enum CompassPoint { case north, south, east, west var description: String { switch self { case .north: return "North" case .south: return "South" case .east: return "East" case .west: return "West" } } } // Enum with associated values enum Result { case success(T) case failure(E) } // MARK: - Access Control public class PublicClass { public var publicProperty = "visible everywhere" private var privateProperty = "only in this class" fileprivate var fileprivateProperty = "only in this file" public init() {} } // MARK: - Property Wrappers @propertyWrapper struct Capitalized { private var value: String = "" var wrappedValue: String { get { value } set { value = newValue.capitalized } } } struct User { @Capitalized var name: String } // MARK: - Async/Await func fetchData() async throws -> String { // Simulate async operation try await Task.sleep(nanoseconds: 1_000_000_000) return "Data fetched" } // MARK: - Generics func swap(_ a: inout T, _ b: inout T) { let temp = a a = b b = temp } // MARK: - Compiler Directives #if DEBUG print("Debug mode") #else print("Release mode") #endif #available(iOS 15.0, *) func modernFeature() { // Use iOS 15+ features } // MARK: - Escaping Keywords let `class` = "This is a keyword used as identifier" let `protocol` = "Another keyword"