0

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.

1
  • 1
    Consider to use NSScanner or – preferable – regular expression to parse HTML. Commented May 16, 2017 at 6:37

1 Answer 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)

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"])
Sign up to request clarification or add additional context in comments.

4 Comments

You didn't know this because it's not in my code example, but dataString is an optional string. That said, flatMap provides the closest result to what I'm looking for. Thanks very much
This doesn't matter. Just add ? after dataString. Modified example to reflect that.
Xcode says it matters because Type String doesn't contain member .components or .dropFirst or .flatMap. Feel free to edit your answer to reflect this, or what I've done is applied this to contentArray as per my question
Thanks much. I somehow missed the .map step when checking your answer the first time. That said, since I already had contentArray created and separated by a string, I did this: let flatMapResult = contentArray.dropFirst().flatMap {$0.components(separatedBy: ",")}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.