-2

I'm a beginner in Swift and I found this code online. I tried asking the author but they wouldn't answer, and because I just started I would really appreciate it if someone could pinpoint the exact reason for the error and how I could fix this. I keep on getting the error "fatal error: unexpectedly found nil while unwrapping an Optional value". I tried finding solutions online but it did not work. Could somebody please kindly help me? Thank you so much! (a bit of explaining would be great! :))

Here is my (well their) code:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate

{
    @IBOutlet weak var pickerView: UIPickerView!


    var pickerDataSource = ["White", "Red", "Green", "Blue"];


    override func viewDidLoad() {

        super.viewDidLoad()
        self.pickerView.dataSource = self; // This is where the error occurs
        self.pickerView.delegate = self;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerDataSource.count;
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return pickerDataSource[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        if(row == 0)
        {
            self.view.backgroundColor = UIColor.whiteColor();
        }
        else if(row == 1)
        {
            self.view.backgroundColor = UIColor.redColor();
        }
        else if(row == 2)
        {
            self.view.backgroundColor =  UIColor.greenColor();
        }
        else
        {
            self.view.backgroundColor = UIColor.blueColor();
        }
    }
Cindy Kim
  • 31
  • 1
  • 4

1 Answers1

1

Connect your UIPickeView outlet from storyboard to your viewcontroller Example : This way Ctrl + Drag I think it should work now . If it's not the problem, comment below.

Aymen BRomdhane
  • 143
  • 1
  • 14
  • Thank you, but it added two more errors, one saying 'Consecutive declarations on a line must be separated by ';'' and 'Expected Declaration'. Is there any way I could solve this issue? Thank you so much! – Cindy Kim Jul 31 '16 at 13:31
  • UPDATE: I fixed the first error 'Consecutive declarations on a line must be separated by ';'', but I don't know how to fix the second. Please help! – Cindy Kim Jul 31 '16 at 14:01
  • UPDATE: I fixed the problem, but I added another code to it to fix it. Thank you for your help! – Cindy Kim Jul 31 '16 at 14:45
  • Not at all , if you need something ;) – Aymen BRomdhane Aug 01 '16 at 08:03