【发布时间】:2017-11-07 03:57:01
【问题描述】:
从具有以下字符串:12#17#15 我想得到一个包含数字的数组:[12, 17, 15]。
我尝试了以下方法,但首先我仍然收到错误 (Cannot convert value of type '[Double?]' to expected argument type 'Double?'),显然,我更喜欢在一张地图上而不是这样的链条上完成所有操作。为什么这些类型不同..?我会说他们应该匹配......
let substrings = records?.split(separator: "#", maxSplits: Int.max, omittingEmptySubsequences: true).map(String.init).map(Double.init)
let objects = substrings.map {value in Model(value: value ?? 0)}
【问题讨论】:
-
为什么你不能只做
yourString.components(separatedBy: "#")或者我不明白你想做什么? -
我没有看到您的代码有任何错误。你能再检查一下吗?
-
let objects = (records ?? "").split(separator: "#").map(Double.init).map(Model.init) -
@LeoDabus 我不喜欢这个解决方案,因为您要映射(迭代)2 次。最好扩展 MacLean 答案:
string.split(separator: "#").map(){Model(value: Double($0) ?? 0)} -
@Vive 是的,只有在更好的情况下才进行迭代。请注意, value 需要一个可选的 Double 所以 nil 不需要合并它。
let objects = (records ?? "").split(separator: "#").flatMap{Model(value: Double($0))}
标签: swift string swift3 casting