picker view generate number 20 to 80

509 Views Asked by At

How can I create a code that generates numbers from 20 to 80? using a pickerviewlet ages = ["20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31 "," 32 "," 33 "," 34 "," 35 "," 36 "," 37 "," 38 "," 39 "," 40 "," 41 "," 42 "," 43 ", "44", "45", "46", "47", "48", "49", "50"] I currently have this but I wanted to know if there is a way to extend it to 80 without needing so much text

1

There are 1 best solutions below

3
Sweeper On BEST ANSWER

You can create the array using a range:

let ages = (20...80).map { "\($0)" }

The map call converts each number to a string.


An even better choice would be not to store all the ages in an array in memory. Notice that the row number + 20 is equal to the age you want to show at that row of the picker view. So you could implement the picker view methods like this:

var selectedAge: Int?
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    61 // there are 61, not 60, numbers from 20 to 80!
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    "\(row + 20)" // for row 0, the row says 20, for row 1, it says 21, for row 2, it says 22, and so on
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // calculate the selected age using the same formula
    selectedAge = row + 20
}