swift-programming

Learn and write Swift code for variables, functions, classes, structs, enums, optionals, closures, protocols, async/await, and SwiftUI.

Audits

Pass

Install

openclaw skills install swift-programming

Swift Programming Skill

Learn and program in Swift - Apple's programming language for iOS, macOS, watchOS, and tvOS.

Quick Reference

Variables & Constants

var nombre = "Juan"          // Variable
let edad = 25                 // Constante
var mensaje: String = "Hola"  // Con tipo explícito

Tipos de Datos

String       // Texto
Int           // Entero
Double        // Decimal
Bool          // true/false
Array         // Lista
Dictionary    // clave-valor
Optional      // puede ser nil

Funciones

func saludar(nombre: String) -> String {
    return "Hola, \(nombre)!"
}

// Parametro con valor por defecto
func greet(_ name: String = "Mundo") -> String {
    return "Hola, \(name)"
}

Clases

class Persona {
    var nombre: String
    var edad: Int
    
    init(nombre: String, edad: Int) {
        self.nombre = nombre
        self.edad = edad
    }
    
    func presentar() -> String {
        return "Soy \(nombre) y tengo \(edad) años"
    }
}

Estructuras

struct Punto {
    var x: Double
    var y: Double
    
    func distancia() -> Double {
        return sqrt(x*x + y*y)
    }
}

Enums

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

enum Status {
    case success(String)
    case failure(Error)
}

Optionals

var nombre: String? = nil  // Puede ser nil

// unwrap seguro
if let nombre = nombre {
    print(nombre)
}

// nil coalescing
let nombreDefecto = nombre ?? "Anonimo"

// optional chaining
let longitud = nombre?.count ?? 0

Closures

let suma = { (a: Int, b: Int) -> Int in
    return a + b
}

// Syntaxis reducida
let multiplicar: (Int, Int) -> Int = { $0 * $1 }

Protocolos

protocol Naming {
    var name: String { get }
    func greet() -> String
}

struct User: Naming {
    var name: String
    
    func greet() -> String {
        return "Hola, \(name)!"
    }
}

Async/Await

func fetchData() async throws -> Data {
    let url = URL(string: "https://api.example.com")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return data
}

// Llamar
Task {
    do {
        let data = try await fetchData()
    } catch {
        print("Error: \(error)")
    }
}

SwiftUI Basics

import SwiftUI

struct ContentView: View {
    @State private var count = 0
    
    var body: some View {
        VStack {
            Text("Contador: \(count)")
            Button("Incrementar") {
                count += 1
            }
        }
    }
}

Recursos