iosswiftvariablesreturnuipickerviewdatasource

Return 2 variables in swift


I'm a newbie developer, trying to return 2 variables but without any success. Here are what I have already tried:

  1. I tried to put these 2 variables (I'm not sure if those are variables or they have different name) into the array and then call return, but the error was:

    "cannot convert return expression of type [Int] to return type int"

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        var typeAndStoreArray = [Int]()
        typeAndStoreArray.append(stores.count)
        typeAndStoreArray.append(types.count)
        return typeAndStoreArray
    }
    
  2. I tried to put stores.count into variable called sc and types.count into variable called tc, but here as well I had an error

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        let sn = stores.count
        let tn = types.count
    
        return (sn, tn)
    }
    

Solution

  • Try to understand the functionality of this delegate method.

    The method is called multiple times for each component. It passes the index of the component and expects to return the corresponding number of rows.

    So if your stores array is component 0 and types is component 1 you have to write

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
         if component == 0 {
            return stores.count
         } else {
            return types.count
         }
    }