James Alexander James Alexander - 1 year ago 105
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 Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download