Alex Kaczynski Alex Kaczynski - 1 year ago 35
Swift Question

Accessing String key to display fetch image (Swift)

I am attempting to access the "major" from my dictionary in my swift class but I cant seem to get the same result as when I am access the name or number. I am trying to correspond the major to a picture associated with each major so it displays in the cell.

import Foundation

class ClassRosterModel {
var studentsRoster = [Dictionary<String, String>] ()
init () {
studentsRoster.append(["name": "Kaz, Alex", "number" : "s0834347", "major" : "SE"])
studentsRoster.append(["name": "O'Rore, Ryan", "number" : "s0835357", "major" : "SE"])
studentsRoster.append(["name": "Lote, Lote", "number" : "s0835357", "major" : "SE"])
studentsRoster.append(["name": "Flora, Nico", "number" : "s0748324", "major" : "MA"])

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("studentCell", forIndexPath: indexPath)

// Configure the cell...
cell.textLabel?.text = studentsList[indexPath.row]["name"]
cell.detailTextLabel?.text = studentsList[indexPath.row]["number"]
print("Student's name: \(studentsList[indexPath.row]["name"])")
print("Student's number: \(studentsList[indexPath.row]["number"])")

return cell

Answer Source

You can make a dictionary to map from your "major" to the image, for example:

let images = [
    "SE": UIImage(named: "se-image.png"),
    "MD": UIImage(named: "another-image.png")
let major = studentsList[indexPath.row]["major"]
if let image = images[major] {
    cell.imageView?.image = image