Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does not conform to protocol UIPickerViewDataSource

I don't know what's wrong with my code. I tried to follow the tutorial but same error happen.

Error:

Type 'FourthViewController' does not conform to protocol 'UIPickerViewDataSource'

Here is my code:

import UIKit

let characters = ["Jaja Bink", "Luke", "Han Solo", "Princess Leia"];

let weapons = ["LightSaber", "Pistol", "Keris"];

class FourthViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var doublePicker: UIPickerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

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


    func pickerView(pickerView: UIPickerView,
                    titleForRow row: Int,
                                forComponent component: Int) -> String? {

        if component == 0 {
            return characters[row]
        } else {
            return weapons[row]
        }

    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int? {
        if component == 0 {
            return characters.count
        } else {
            return weapons.count
        }
    }

}
like image 243
Ayus Salleh Avatar asked Aug 29 '16 05:08

Ayus Salleh


2 Answers

Replacing deprecated version of the method of protocol UIPickerViewDataSource, if you're using Swift 3 could works for you.

Deprecated Method of Protocol

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

Latest Method of Protocol in Swift 3

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

Note: Same true for other required protocol methods. i.e

Deprecated:

func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int

Recent Version:

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int

like image 185
Aamir Avatar answered Nov 07 '22 06:11

Aamir


Because your required delegate method is not correct.

Replace it with this:

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if component == 0 {
        return characters.count
    } else {
        return weapons.count
    }
}

Your delegate method returns Int? which is not correct.

like image 39
Dharmesh Kheni Avatar answered Nov 07 '22 07:11

Dharmesh Kheni