Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an Int array into a String? array in Swift

I have an array that looks like this:

var arr: [Int] = [1,2,3,4,5] 

In order to print this, I would like to convert this to:

var newArr: [String?] = ["1","2","3","4","5"] 

How can I solve this problem?

like image 571
GJZ Avatar asked Jun 23 '15 13:06

GJZ


1 Answers

Airspeed Velocity gave you the answer:

var arr: [Int] = [1,2,3,4,5]  var stringArray = arr.map { String($0) } 

Or if you want your stringArray to be of type [String?]

var stringArray = arr.map  { Optional(String($0)) } 

This form of the map statement is a method on the Array type. It performs the closure you provide on every element in the array, and assembles the results of all those calls into a new array. It maps one array into a result array. The closure you pass in should return an object of the type of the objects in your output array.

We could write it in longer form:

var stringArray = arr.map {   (number: Int) -> String in   return String(number) } 

EDIT:

If you just need to install your int values into custom table view cells, you probably should leave the array as ints and just install the values into your cells in your cellForRowAtIndexPath method.

func tableView(tableView: UITableView,    cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {   let cell = tableView.dequeueReusableCellWithIdentifier("cell",      forIndexPath: indexPath) as! MyCustomCellType   cell.textLabel?.text = "\(arr[indexPath.row])"   return cell } 

Edit #2:

If all you want to to is print the array, you'd be better off leaving it as an array of Int objects, and simply printing them:

arr.forEach { print($0) } 
like image 164
Duncan C Avatar answered Oct 02 '22 15:10

Duncan C