1

I need to populate an array using data from a database. When I do that I am getting an error message from my pickerView function. Before, I had this array hard coded as below and now I want that coming from a database query.

var recomendMedsTypes = ["Advil","Aleve", "Ibuprofen","Tylenol"]

I am not sure if I am designing my array correctly. The array is populated from a function based on the simple class below

class Medicine {
    var dawa: String

    init(dawa: String) {
        self.dawa = dawa
    }
}

I populate an instance of this class as below

var medname = [Medicine]()

Here is the function to populate the array

func readMedName() -> Array<Any>{

       //get data from this query
       let queryString = "SELECT drugName FROM otc"

       //statement pointer
       var stmt2:OpaquePointer?

       //preparing the query
       if sqlite3_prepare(db, queryString, -1, &stmt2, nil) != SQLITE_OK {
           let errmsg = String(cString: sqlite3_errmsg(db)!)
           print("error preparing read: \(errmsg)")
           //return errmsg
       }

       //go through all the records
      while(sqlite3_step(stmt2) == SQLITE_ROW){
           let drugname = String(cString: sqlite3_column_text(stmt2,0))

        // populate array
       medname.append(Medicine(dawa: String(describing: drugname)))

       }
       return medname
   }

Here is my attempt to populate the array from the query

var recomendMedsTypes = readMedName()

In the pickerView

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

return recomendMedsTypes[row]
}

Here I get the error “Cannot convert return expression of type ‘Any’ to return type ’String?’. How do I design the array and the call to return query data? The query should return a list of drugs.

1 Answers1

0

Why do you declare the return type of the method Array<Any> although you clearly know that's Array< Medicine> aka [Medicine]?

In Swift declare the types as specific as possible.

func readMedName() -> [Medicine] {

By the way as medname is declared outside of the method the return value is redundant

func readMedName() {
...
// return medname
}

This fixes the error but your will get another one. You have to return a string from titleForRow in your case the dawa property

return recomendMedsTypes[row].dawa

And please don't create a string from describing a string. That's pointless

medname.append(Medicine(dawa: drugname))

Finally most likely you don't need a class, a struct is suffienct and you get the initializer for free. If dawa doesn't change declare it even as constant

struct Medicine {
    let dawa: String
}
vadian
  • 274,689
  • 30
  • 353
  • 361