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

标签 ios arrays swift casting type-conversion

我有一个如下所示的数组:

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

为了打印这个,我想把它转换成:

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

我该如何解决这个问题?

最佳答案

Airspeed Velocity 给了你答案:

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

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

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

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

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

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

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

编辑:

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

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
}

编辑#2:

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

arr.forEach { print($0) }

关于ios - 如何将 Int 数组转换为 String? Swift 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31003977/

相关文章:

ios - Swift 4 中的 statusBarStyle

ios - Swift 将大高度标签插入 View

javascript - React中map函数的数组

arrays - 在不更改输入的情况下查找数组中的重复项?

ios - NWConnection 发送多个数据报

ios - 检测用户是否在应用商店中对应用进行了评分

ios - GLSL ES 裁剪顶点到远平面

ios - 如何在钥匙串(keychain) iOS 中保存 UUID?

ios - 模仿Facebook隐藏/显示扩展/收缩导航栏

javascript - Angular 无法读取数组中的对象