Return 2 variables in swift

329 Views Asked by At

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

There are 2 best solutions below

0
vadian On BEST ANSWER

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
     }
}
0
Fangming On

You are misusing picker view. To have two wheels of values, you need to return counts for each wheel separately. A component in picker view is like the wheel. So, to have the first wheel (component) displaying stores and then second wheel displaying types, you need to return counts separately like this

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