ios 如何将 Int 数组转换为 String?Swift 中的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31003977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:34:33  来源:igfitidea点击:

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

iosarraysswiftcastingtype-conversion

提问by GJZ

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"]

Please help me out! Thanks in advance.

请帮帮我!提前致谢。

回答by Duncan C

Airspeed Velocity gave you the answer:

空速速度给你答案:

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

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

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

或者,如果您希望 stringArray 为类型 [String?]

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
}

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.

这种形式的 map 语句是 Array 类型上的一种方法。它对数组中的每个元素执行您提供的闭包,并将所有这些调用的结果组装到一个新数组中。它将一个数组映射到一个结果数组。您传入的闭包应返回输出数组中对象类型的对象。

We could write it in longer form:

我们可以把它写成更长的形式:

arr.forEach { print(
 cell.textLabel?.text = "\(arr[indexPath.row])"
) }

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.

如果您只需要将 int 值安装到自定义表格视图单元格中,您可能应该将数组保留为 ints,并将这些值安装到 cellForRowAtIndexPath 方法中的单元格中。

##代码##

Edit #2:

编辑#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:

如果您只想打印数组,最好将其保留为 Int 对象数组,然后简单地打印它们:

##代码##

回答by K123

You should use

你应该使用

##代码##

in order to present the value in the label as a String.

以便将标签中的值显示为字符串。