Swift Cheat Sheet

Here’s a Swift cheat sheet:

Basic Syntax

// Variables and Constants
var variable = "Hello, Swift!"
let constant = 42

// Data Types
let integer: Int = 10
let double: Double = 3.14
let boolean: Bool = true
let string: String = "Swift"

// Optionals
var optionalValue: Int? = nil

// String Interpolation
let name = "John"
let greeting = "Hello, \(name)!"

// Arrays and Dictionaries
var numbers = [1, 2, 3]
var person = ["name": "John", "age": 25]

// Control Flow
if condition {
    // Code to execute
} else {
    // Code to execute if the condition is false
}

for item in collection {
    // Code to repeat
}

// Functions
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

// Classes and Structures
class MyClass {
    var property: String
    
    init(property: String) {
        self.property = property
    }
}

struct MyStruct {
    var property: String
}

Optionals

// Optional Binding
if let unwrappedValue = optionalValue {
    // Use unwrappedValue
} else {
    // Value is nil
}

// Nil Coalescing Operator
let result = optionalValue ?? defaultValue

Enums

enum CompassDirection {
    case north, south, east, west
}

let direction = CompassDirection.north

Closures

// Basic Closure
let greetingClosure = {
    print("Hello, Swift!")
}

// Closure with Parameters and Return Type
let sumClosure: (Int, Int) -> Int = { (a, b) in
    return a + b
}

// Using Closures
let numbers = [1, 2, 3, 4, 5]
let doubledNumbers = numbers.map { $0 * 2 }

Error Handling

enum MyError: Error {
    case customError
}

func myFunction() throws {
    throw MyError.customError
}

do {
    try myFunction()
} catch {
    print("An error occurred: \(error)")
}

Protocols

protocol MyProtocol {
    func myMethod()
}

class MyClass: MyProtocol {
    func myMethod() {
        // Implementation
    }
}

Extensions

extension String {
    func customMethod() {
        // Custom method for String
    }
}

let myString = "Swift"
myString.customMethod()

Option Set

struct Permissions: OptionSet {
    let rawValue: Int
    
    static let read = Permissions(rawValue: 1 << 0)
    static let write = Permissions(rawValue: 1 << 1)
    static let execute = Permissions(rawValue: 1 << 2)
}

let myPermissions: Permissions = [.read, .write]

SwiftUI (Basic View)

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!")
            .font(.largeTitle)
            .foregroundColor(.blue)
    }
}

// Use ContentView in your SwiftUI app

Playground Tips

  • Use Xcode Playgrounds for interactive Swift coding.
  • Explore Swift standard library functions and methods.

This Swift cheat sheet covers basic syntax, optionals, enums, closures, error handling, protocols, extensions, option sets, SwiftUI, and playground tips. Customize as needed for your specific Swift programming needs.