[SOLVED] Return a dictionary from multiple line string in swift

Issue

I am new to swift. Is there a simple way to convert the following string to dictionary format.

Example:

input = "Name: Jack\\n Area: Place\\n FavColor: Blue\\n"

Expected Output:

dict = \[Name: Jack, Area: Place, FavColor: Blue\]

and also leading spaces should be trimmed.

The key-value pairs are always in new line.

My idea is split the string based on new line characters first

lines = input.components(separatedBy: CharacterSet.newlines)

then iterate through lines and split each line based on ":" and put them into dict.

Is there any other efficient way to do it?

Solution

A possible solution is Regular Expression, it searches for the pattern word - colon - whitespace(s) - word and captures both words

let input = "Name: Jack\n Area: Place\n FavColor: Blue\n"

let pattern = "(\\b.*\\b):\\s+(\\b.*\\b)" // or "(\\w+):\\s+(\\w+)"
let regex = try! NSRegularExpression(pattern: pattern)
var result = [String:String]()
regex.matches(in: input).forEach { match in
    if let keyRange = Range(match.range(at: 1), in: input),
       let valueRange = Range(match.range(at: 2), in: input) {
        result[String(input[keyRange])] = String(input[valueRange])
    }
}

print(result)

Answered By – vadian

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *