I have a class called Room where I store information about a particular room in my home (its name, an image of it, etc). In my main ViewController, I create an array of Rooms and assign them some values. Later on, I want to search that array of Rooms for the room named "Study Room." I can use
func findARoom(named room: String) -> Room {
for i in 0..<rooms.count {
if rooms[i].roomName == room {
return rooms[i]
}
}
}
but I think there is a better way. I want to be able to call the findARoom() function in the same way but not iterate through the entire array. I have used Maps in C++, where some linked values are hashed into the map and you can search for one of the values using the other value (e.g. find a phone number attached to someone's last name). Is there any way I can use a similar structure in Swift to find a Room object based on its roomName parameter?
Room.swift:
import UIKit
struct Room {
var roomName: String
var roomImage: UIImage
var port: UInt16
init(roomName: String, roomImage: UIImage, port: UInt16 = 1883) {
self.roomName = roomName
self.roomImage = roomImage
self.port = port
}
}
ViewController:
import UIKit
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, RoomCellDelegate, MQTTModelDelegate {
var server = [MQTTModel()]
let cellId = "cellId"
var rooms: [Room] = [Room]()
var roomTableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
createRoomArray()
findARoom(named: "Study Room")
}
// Setting up the array of rooms
func createRoomArray() {
rooms.append(Room(roomName: "Living Room", roomImage: UIImage(named: "Living_Room")!, port: 48712))
rooms.append(Room(roomName: "Study Room", roomImage: UIImage(named: "Study_Room")!, port: 1883))
rooms.append(Room(roomName: "Bedroom", roomImage: UIImage(named: "Bedroom")!, port: 1883))
}
func findARoom(named room: String) -> Room {
for i in 0..<rooms.count {
if rooms[i].roomName == room {
return rooms[i]
}
}
}
}