1

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 Answers1

1

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
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    you can also use description property as the KeyPath (Swift 5.2). `(20...80).map(\.description)` – Leo Dabus Jul 03 '20 at 02:03
  • @LeoDabus Yes, but I personally like the look and feel of string interpolation. I think it shows more vividly the transformation from `20` to `"20"`. :) – Sweeper Jul 03 '20 at 02:07
  • I usually avoid using a closure whenever I can. I think in this case I would just pass the `String.init`. – Leo Dabus Jul 03 '20 at 02:09