home ~ projects ~ socials

Get The Item Selected In A List From An Array In Swift

import SwiftUI

struct Ocean: Identifiable, Hashable {
    let name: String
    let id = UUID()
}

struct ContentView: View {
    @State private var selectedOceanId = UUID()
    
    private var oceans = [
        Ocean(name: "Pacific"),
        Ocean(name: "Atlantic"),
        Ocean(name: "Indian"),
        Ocean(name: "Southern"),
        Ocean(name: "Arctic")
    ]
    
    func selectedOcean() -> Ocean? {
        guard let oceanId = oceans.firstIndex(where: { $0.id == selectedOceanId })
        else {
            return Optional.none
        }
        return oceans[oceanId]
    }
    
    func selectedOceanName() -> String {
        selectedOcean()?.name ?? "none"
    }

    var body: some View {
        VStack {
            List(oceans, selection: $selectedOceanId) {
                Text($0.name)
            }
            Text("Current Ocean: \(selectedOceanName())")
        }
    }
}

#Preview {
    ContentView()
}
-- end of line --