Created
June 20, 2024 14:07
-
-
Save vikaskore/078a11214ba97a897bb64e3440f7e7b6 to your computer and use it in GitHub Desktop.
In this you will find logic of 3 fruit basket(apple, orange and mixture) puzzle implemented in Swift and SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// FruitBaskets.swift | |
// Samples | |
// | |
// Created by VikasK on 20/06/24. | |
// Copyright © 2024 Vikaskore Software. All rights reserved. | |
// | |
import SwiftUI | |
enum Fruit { | |
case apple | |
case orange | |
} | |
enum BasketLabel: String { | |
case apples = "Apples" | |
case oranges = "Oranges" | |
case mixture = "Mixture" | |
} | |
class Basket { | |
var label: BasketLabel | |
var contents: [Fruit] | |
init(label: BasketLabel, contents: [Fruit]) { | |
self.label = label | |
self.contents = contents | |
} | |
func pickOneFruit() -> Fruit { | |
return contents.first! | |
} | |
} | |
struct FruitBaskets: View { | |
@State private var correctLabels: [BasketLabel: BasketLabel] = [:] | |
@State private var baskets: [Basket] = [ | |
Basket(label: .apples, contents: [.apple, .orange]), | |
Basket(label: .oranges, contents: [.apple, .orange]), | |
Basket(label: .mixture, contents: [.orange]) | |
] | |
@State private var showResult = false | |
var body: some View { | |
VStack { | |
Text("Basket Labeling Puzzle") | |
.font(.largeTitle) | |
.padding() | |
ForEach(baskets, id: \.label) { basket in | |
HStack { | |
Text("Basket labeled \(basket.label.rawValue)") | |
Button(role: .none) { | |
self.solvePuzzle(byPickingFrom: basket) | |
} label: { | |
Text("Pick a fruit") | |
} | |
.padding() | |
.background(Color.blue) | |
.foregroundColor(.white) | |
} | |
.padding() | |
} | |
if showResult { | |
VStack { | |
Text("Correct Labels:") | |
.font(.title2) | |
ForEach(BasketLabel.allCases, id: \.self) { label in | |
if let correctLabel = correctLabels[label] { | |
Text("The basket labeled \(label.rawValue) should actually be labeled \(correctLabel.rawValue)") | |
} | |
} | |
} | |
.padding() | |
} | |
} | |
} | |
func solvePuzzle(byPickingFrom basket: Basket) { | |
let pickedFruit = basket.pickOneFruit() | |
if pickedFruit == .apple { | |
correctLabels[.mixture] = .apples | |
correctLabels[.oranges] = .mixture | |
correctLabels[.apples] = .oranges | |
} else { | |
correctLabels[.mixture] = .oranges | |
correctLabels[.apples] = .mixture | |
correctLabels[.oranges] = .apples | |
} | |
showResult = true | |
} | |
} | |
extension BasketLabel: CaseIterable {} | |
#Preview { | |
FruitBaskets() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment