【问题标题】:Convert a 2d array of strings to a 2d array of double swift将二维字符串数组转换为二维二维数组
【发布时间】:2019-01-23 14:50:29
【问题描述】:

我有 2 个数组:

var locationString = [[String]]()
var doubleArray = [[Double]]()

在解析器运行后附加数组数据,以防您想知道为什么没有数据。

基本上我正在尝试将 locationString 从字符串转换为双精度。 我最初尝试了以下方法:

let doubleArray = locationString.map{ Double($0) }

但这似乎不起作用,因为我收到以下错误:

Cannot invoke initializer for type 'Double' with an argument list of type ((String]))

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • let doubleArray = locationString.map{$0.compactMap(Double.init)}

标签: arrays swift string type-conversion double


【解决方案1】:

使用mapcompactMap 映射:

let doubleArray = locationString.map { $0.compactMap(Double.init) }

示例:

let locationString = [["1.2", "2.3"], ["3.4", "4.4", "hello"]]

let doubleArray = locationString.map { $0.compactMap(Double.init) }

print(doubleArray) // [[1.2, 2.3], [3.4, 4.4]]

外部map 处理每个字符串数组。内部 compactMapStrings 转换为 Double 并在转换返回 nil 时丢弃它们,因为 String 不是有效的 Double


要在转换为 Double 之前修剪 Strings 中的前导和尾随空格,请使用 .trimmingCharacters(in: .whitespaces)

let doubleArray = locationString.map { $0.compactMap { Double($0.trimmingCharacters(in: .whitespaces )) } }

【讨论】:

  • 这似乎是正确的,尽管由于某种原因,当我尝试打印数据时,输出只是 [[], [], [], [], []] 对它为什么这样做有任何想法吗?
  • 检查您的输入。 Strings 不能有前导或尾随空格。如果需要,您也可以修剪它们。
  • 是的,在附加数据后打印locationString 时,我刚刚注意到一些事情。数据没有被应有的逗号分隔,例如,第一个元素如下所示:[["55.949636-3.19108]] 我相信这很可能是原因,当它用逗号分隔数据时你有什么帮助吗是附加的吗?
  • 原始输入是什么样的?
  • 所以原始输入是从一些 XML 数据中提取的,它被作为字符串提取(这绝对是我的错,但在这一点上它比更改原始代码更容易解​​决)。数据附加到数组中:locationString.append([myTrail.trailLatitude + myTrail.trailLongitude]) 当您打印 locationString 数组的数据时,它看起来像这样:[["55.949636-3.19108]]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多