Search code examples
iosswiftnsarrayuipicker

Getting titleForRow Using UIPicker from NSArray - Swift


I'm trying to return the object from my array using a UIPickerViewDelegate below:

var myArr = NSArray()

Adding objects to my array

self.myArray = NSArray(objects: "Mr", "Mrs", "Miss", "Ms", "Dr", "Master", "Rev",
            "Fr", "Atty", "Prof", "Hon")

Here is my delegate

func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
    var string = NSString(coder: self.myArray.objectAtIndex(row) as NSCoder)
    return string
}

However this throws an exception. How do i do this simple task?


Solution

  • Based solely on your question, and assuming there's nothing relevant you haven't mentioned, get rid of the coder stuff:

    func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
        return self.myArray.objectAtIndex(row) as NSString
    }
    

    Since this is a swift program, you should also probably not be using NSArray since that results in type ambiguity:

    var myArr = ["Mr", "Mrs", "Miss", "Ms", "Dr", "Master", "Rev",
            "Fr", "Atty", "Prof", "Hon"]
    

    And now your delegate method becomes even clearer:

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