Alex Kaczynski Alex Kaczynski - 6 months ago 34
Swift Question

Assigning image to key value (Swift)

I am trying to assign an image for different majors in my dictionary ex SE, CS, default but each time I run the program it crashes on me. I am using a tableview and have a subtile style. Should I be assigning something to the majors first? Here is my tableviewcontroller

import UIKit
class ClassRosterTableViewController: UITableViewController {

var studentsList = [Dictionary<String, String>]()

override func viewDidLoad() {
super.viewDidLoad()

let myStudentRoster = ClassRosterModel()
studentsList = myStudentRoster.studentsRoster
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

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"])")
print("Student's email: \(studentsList[indexPath.row]["email"])")

if let major = studentsList[indexPath.row]["major"] {
switch (major) {
case "SE":

cell.imageView?.image = UIImage(named:"SE")!

case "CS":

cell.imageView?.image = UIImage(named:"CS")!
default:
cell.imageView?.image = UIImage(named:"default")!
}
}

return cell
}


//here is my separate class for the studentslist

import Foundation

class ClassRosterModel {

var studentsRoster = [Dictionary<String, String>] ()
init () {

studentsRoster.append(["name": "Kaczynski, Alex", "major" : "SE", "email" : "s\(rand1)@monmouth.edu", "currentTerm" : "Spring", "numberOfCredits" : "\(rand2)" ])
studentsRoster.append(["name": "O'Rore, Ryan", "major" : "SE", "email" : "s\(rand1)@monmouth.edu", "currentTerm" : "Fall", "numberOfCredits" : "\(rand2)" ])
}
}

Answer

You are force unwrapping those images and if they are not present in your app's bundle it will crash. UIImageView's image property is optional so it's fine to assign those images without unwrapping them:

    if let major = studentsList[indexPath.row]["major"] {
        switch (major) {
        case "SE":
            cell.imageView?.image =  UIImage(named:"SE")
        case "CS":
            cell.imageView?.image =  UIImage(named:"CS")
        default:
            cell.imageView?.image =  UIImage(named:"default")
        }
    }

Note: if the images aren't present in your bundle, your imageView will be empty, but at least it won't crash.