I currently have an array being created like this
我目前有一个像这样创建的数组
let stringSeparator1 = "some string"
if let contentArray = dataString?.components(separatedBy: stringSeparator1) {
if contentArray.count > 1 {
//Separate contentArray into array of relevant results
let stringSeparator2 = "</p>"
let result = contentArray[1].components(separatedBy: stringSeparator2)
This works great for 1 index position of contentArray. But what I really want to do is go through contentArray from index 1 to contentArray.count and delimit all of the data by stringSeparator2. I've tried several methods using loops and can't find a way that gives me what I need.
这适用于contentArray的1个索引位置。但我真正想做的是从index1到contentArray.count的contentArray,并通过stringSeparator2分隔所有数据。我已经尝试了几种使用循环的方法,但找不到能够满足我需要的方法。
1 个解决方案
#1
1
Use .map
to get array of arrays and .flatMap
to get array of strings. You can use various filtering methods (e.g. .filter
, .dropFirst
, .dropLast
, .dropWhile
, etc)
使用.map获取数组数组和.flatMap获取字符串数组。您可以使用各种过滤方法(例如.filter,.dropFirst,.dropLast,.dropWhile等)
let dataString: String? = "0-1-2,3-4-5,6-7-8"
// map will result in array of arrays of strings. dropFirst will skip first part (see dropLast, etc)
let mapResult = dataString?.components(separatedBy: ",").dropFirst().map { $0.components(separatedBy: "-") }
print(mapResult) // Optional([["3", "4", "5"], ["6", "7", "8"]])
// flatMap will result in array of strings. dropFirst will skip first part (see dropLast, etc)
let flatMapResult = dataString?.components(separatedBy: ",").dropFirst().flatMap { $0.components(separatedBy: "-") }
print(flatMapResult) // Optional(["3", "4", "5", "6", "7", "8"])
#1
1
Use .map
to get array of arrays and .flatMap
to get array of strings. You can use various filtering methods (e.g. .filter
, .dropFirst
, .dropLast
, .dropWhile
, etc)
使用.map获取数组数组和.flatMap获取字符串数组。您可以使用各种过滤方法(例如.filter,.dropFirst,.dropLast,.dropWhile等)
let dataString: String? = "0-1-2,3-4-5,6-7-8"
// map will result in array of arrays of strings. dropFirst will skip first part (see dropLast, etc)
let mapResult = dataString?.components(separatedBy: ",").dropFirst().map { $0.components(separatedBy: "-") }
print(mapResult) // Optional([["3", "4", "5"], ["6", "7", "8"]])
// flatMap will result in array of strings. dropFirst will skip first part (see dropLast, etc)
let flatMapResult = dataString?.components(separatedBy: ",").dropFirst().flatMap { $0.components(separatedBy: "-") }
print(flatMapResult) // Optional(["3", "4", "5", "6", "7", "8"])