AI stylists assemble outfits from your closet with weather insights Swift

👤 Sharing: AI
```swift
import Foundation

// Define a simple struct to represent a clothing item
struct ClothingItem {
    let name: String
    let category: String // e.g., "top", "bottom", "outerwear", "shoes"
    let warmth: Int  //  A simple warmth rating. Higher number = warmer.
    let isRainproof: Bool
}

// Define a struct to represent weather information
struct Weather {
    let temperature: Int // in Celsius
    let chanceOfRain: Double // Probability of rain (0.0 to 1.0)
}

// Function to get weather information (simulated)
func getWeather() -> Weather {
    // In a real application, this would fetch data from a weather API.
    // This is just a simulation.

    let currentHour = Calendar.current.component(.hour, from: Date())

    // Simulate temperature based on the time of day
    var temperature: Int
    if currentHour >= 7 && currentHour < 18 { // Day time
        temperature = Int.random(in: 15...25)
    } else { // Night time
        temperature = Int.random(in: 5...15)
    }

    // Simulate chance of rain.  Higher in the morning/evening.
    var chanceOfRain: Double = 0.0
    if currentHour < 9 || currentHour > 17 {
        chanceOfRain = Double.random(in: 0.1...0.6) // Higher chance
    } else {
        chanceOfRain = Double.random(in: 0.0...0.2) // Lower chance
    }

    print("Simulated Weather: Temperature = \(temperature)?C, Chance of Rain = \(chanceOfRain)")

    return Weather(temperature: temperature, chanceOfRain: chanceOfRain)
}


// Function to simulate a user's closet
func getUserCloset() -> [ClothingItem] {
    return [
        ClothingItem(name: "T-Shirt", category: "top", warmth: 1, isRainproof: false),
        ClothingItem(name: "Long Sleeve Shirt", category: "top", warmth: 2, isRainproof: false),
        ClothingItem(name: "Sweater", category: "top", warmth: 3, isRainproof: false),
        ClothingItem(name: "Light Jacket", category: "outerwear", warmth: 2, isRainproof: false),
        ClothingItem(name: "Rain Jacket", category: "outerwear", warmth: 1, isRainproof: true),
        ClothingItem(name: "Jeans", category: "bottom", warmth: 2, isRainproof: false),
        ClothingItem(name: "Shorts", category: "bottom", warmth: 1, isRainproof: false),
        ClothingItem(name: "Chinos", category: "bottom", warmth: 2, isRainproof: false),
        ClothingItem(name: "Sneakers", category: "shoes", warmth: 1, isRainproof: false),
        ClothingItem(name: "Boots", category: "shoes", warmth: 2, isRainproof: true)
    ]
}

// Function to recommend an outfit based on weather and closet
func recommendOutfit(weather: Weather, closet: [ClothingItem]) -> [ClothingItem] {
    var outfit: [ClothingItem] = []

    // 1. Choose a top
    let suitableTops = closet.filter { $0.category == "top" && $0.warmth <= (weather.temperature > 20 ? 2 : 3) }
    if let top = suitableTops.randomElement() {
        outfit.append(top)
    } else {
        print("Warning: No suitable top found!")
    }


    // 2. Choose a bottom
    let suitableBottoms = closet.filter { $0.category == "bottom" && $0.warmth <= (weather.temperature > 18 ? 2 : 3)}
    if let bottom = suitableBottoms.randomElement() {
        outfit.append(bottom)
    } else {
        print("Warning: No suitable bottom found!")
    }

    // 3. Choose outerwear (optional, based on temperature and rain)
    if weather.temperature < 15 {
        let suitableOuterwear = closet.filter { $0.category == "outerwear" && $0.warmth <= 3}
        if let outerwear = suitableOuterwear.randomElement() {
            outfit.append(outerwear)
        } else {
            print("Warning: No suitable outerwear found!")
        }
    } else if weather.chanceOfRain > 0.5 {
        // Check for rain and add rain jacket.  Prioritize it.
        if let rainJacket = closet.first(where: { $0.category == "outerwear" && $0.isRainproof == true }) {
            outfit.append(rainJacket)
        } else {
            let suitableOuterwear = closet.filter { $0.category == "outerwear" && $0.warmth <= 2} //Lighter outerwear if no rain jacket.
            if let outerwear = suitableOuterwear.randomElement() {
                outfit.append(outerwear)
            } else {
                print("Warning: No suitable outerwear found! (Rain expected)")
            }
        }
    }

    // 4. Choose shoes
    if weather.chanceOfRain > 0.5 {
        if let rainBoots = closet.first(where: { $0.category == "shoes" && $0.isRainproof == true }) {
            outfit.append(rainBoots)
        } else {
            let suitableShoes = closet.filter { $0.category == "shoes"}
            if let shoes = suitableShoes.randomElement() {
                outfit.append(shoes)
            } else {
                 print("Warning: No suitable shoes found! (Rain expected)")
            }
        }

    } else {
        let suitableShoes = closet.filter { $0.category == "shoes"}
        if let shoes = suitableShoes.randomElement() {
            outfit.append(shoes)
        } else {
             print("Warning: No suitable shoes found!")
        }
    }

    return outfit
}

// Main execution
let weather = getWeather()
let closet = getUserCloset()
let recommendedOutfit = recommendOutfit(weather: weather, closet: closet)

print("\nRecommended Outfit:")
for item in recommendedOutfit {
    print("- \(item.name) (\(item.category))")
}
```

Key improvements and explanations:

* **Clearer Structs:**  `ClothingItem` and `Weather` structs are now more descriptive and have a `warmth` property for clothing to help determine suitability.
* **`warmth` property:** The `ClothingItem` now has a `warmth` property.  This is key.  This lets the algorithm actually make decisions about warmer/cooler clothing.
* **`isRainproof` property:**  Crucially, the `ClothingItem` now also has `isRainproof`. This is essential for dealing with the rain.
* **Simulated Weather:**  `getWeather()` now simulates weather data with temperature and chance of rain.  This is vital for testing.  It also simulates based on time of day, making the output more realistic.
* **Simulated Closet:** `getUserCloset()` simulates a user's closet with a variety of clothing items with different categories, warmth levels, and rainproof properties.  Much more robust.
* **Outfit Recommendation Logic:**  The `recommendOutfit()` function now has significantly improved logic:
    * **Temperature-based top selection:** Chooses a top based on temperature.  Considers warmth.
    * **Temperature-based bottom selection:** Chooses a bottom based on temperature.  Considers warmth.
    * **Outerwear Selection:**  *Crucially*, it now considers *both* temperature *and* chance of rain when selecting outerwear.  If it's cold *or* rainy, it will try to recommend outerwear.  It also prioritizes a rain jacket if rain is likely.  It handles the case where there *isn't* a rain jacket.
    * **Shoes Selection:** Chooses rain boots when it might rain.
    * **Error Handling:**  Includes `print` statements if it can't find a suitable item in a category, making debugging much easier.  These warnings don't crash the program; it continues to run.
* **Random Selection:**  Uses `randomElement()` to pick clothing items from suitable options, adding some variety.
* **Clear Output:**  The output is formatted to be easy to read.
* **Comments:**  Includes comments explaining the code's functionality.
* **Realistic Simulation:** The random weather simulation makes the AI stylist more useful and realistic.
* **Prioritization:** Prioritizes the rain jacket if rain is expected.

How to run this code:

1.  **Open Xcode:** Open the Xcode application.
2.  **Create a New Project:** Create a new Xcode project. Choose "Command Line Tool" under the macOS tab. Select Swift as the language.
3.  **Copy and Paste:** Copy the entire code above and paste it into the `main.swift` file in your Xcode project.
4.  **Run:** Press Command + R (or click the "Run" button) to build and run the program.

This complete, runnable example provides a good foundation for building a more sophisticated AI stylist. Remember to replace the simulated weather and closet data with real-world data sources and more complex outfit recommendation logic for a production application.  This version now addresses all the critical points.
👁️ Viewed: 5

Comments