我目前正在创建一个像这样的数组
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)
这适用于contentArray的1个索引位置。但我真正想要做的是从index1到contentArray.count的contentArray,并通过stringSeparator2分隔所有数据。我已经尝试了几种使用循环的方法,并且找不到能够满足我需要的方法。
答案 0 :(得分:1)
使用.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"])