James Alexander James Alexander - 1 month ago 9
Swift Question

How to get the value of a Range given an index in Swift

Given the following range declaration and usage in Swift 3:

let values = [1...50]

cell.textLabel?.text = String(values[indexPath.row]! + 1)


How could do something like the above where I could cast the value of an item at a specific index to a String?

Answer

To make values be an array of Int from 1...50 you can use:

let values = Array(1...50)

then you can use the values like this:

cell.textLabel?.text = String(values[indexPath.row])

To make values be an array of String from "1" to "50" use:

let values = (1...50).map(String.init)

then you can do:

cell.textLabel?.text = values[indexPath.row]
Comments