'I can't figure out how to write a function inside a class using Dictionary. Thanks
class Car {
let color: String
let model: String
var doors: [Int:String] = [:]
let brand: String
let state: String
init (color: String, model: String, doors: [Int:String], brand: String, state: String) {
self.color = color
self.model = model
self.doors = doors
self.brand = brand
self.state = state
}
func openDoor (numberDoor: Int) {
}
func closeDoor (numberDoor: Int) {
}
}
let car = Car(color: "Black", model: "A8", doors: [1:"Door #1", 2: "Door #2"], brand: "Audi", state: "Stop")
I enter the door number and it displays a message on the console that "the door is open", if I enter it again with the same number - the message that "the door is ALREADY open". Door numbers are recorded in the Dictionary.
Example car.openDoor(number: 2) // "Door 2 is opened" car.openDoor(number: 2) // "Door 2 IS ALREADY OPENED
Solution 1:[1]
var alreadyOpen: [Int] = []
func openDoor (numberDoor: Int) {
if alreadyOpen.contains(numberDoor) {
print("door is already opend")
} else {
print("door is open")
alreadyOpen.append(numberDoor)
}
}
create a var with name "alreadyOpen"
var alreadyOpen: [Int] = []
below Condition menning if this number is available in [alreadyOpen] array so print("door is already opend") else print("door is open") and add a element in array.
if alreadyOpen.contains(numberDoor)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
