Ben*_*Ben 0 arrays swift swift3
我想从一个字符串创建一个整数数组[Int],该字符串应该包含一个逗号分隔列表.
以下是一些有效的输入:
1
1,2,3
1,5,10
Run Code Online (Sandbox Code Playgroud)
以下是一些无效输入:
[nil] // no value set
1,,2,3 // extra commas
1,Z,10 // characters other than numbers and commas
Run Code Online (Sandbox Code Playgroud)
我已经设法为第一部分提出了一些东西,即使用以下代码将值分离出来:
func get_numbers() -> Array<Int>{
return self.numbers_as_csv_string!
.components(separatedBy: ",")
.map { word in Int(word.trimmingCharacters(in: CharacterSet.whitespaces))! }
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,该代码不处理上面列出的无效输入,并且应用程序在大多数情况下都会崩溃.添加一些检查的最佳方法是什么,这样如果存在无效列表,我们只返回一个[1]?我想尽可能最短的代码 - 是一个正则表达式最好的方式去这里?
提前谢谢了!
而不是使用!强制解包,用于flatMap忽略无法转换为的组件Int:
func get_numbers() -> Array<Int> {
return self.numbers_as_csv_string!
.components(separatedBy: ",")
.flatMap {
Int($0.trimmingCharacters(in: .whitespaces))
}
}
Run Code Online (Sandbox Code Playgroud)
样品结果:
1 => [1]
1,2,3 => [1,2,3]
1,5,10 => [1,5,10]
nil => []
1,,2,3 => [1,2,3]
1,Z,10 => [1,10]
Run Code Online (Sandbox Code Playgroud)