Does not conform to protocol UIPickerViewDataSource

Ayus Salleh picture Ayus Salleh · Aug 29, 2016 · Viewed 11.1k times · Source

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
        }
    }

}

Answer

Aamir picture Aamir · Dec 27, 2016

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