skip to Main Content

I have a string with many pipes I want to convert them into dictionary [String:Any] how can I do that ?

Example

let input = "boolFirst=false|onProject=Active|passed=false"

Into -->

let output = [String: Any] = [boolFirst: false, onProject: "Active", passed: false]

so far tried with components(separatedBy: "|") & components(separatedBy: "=")
Is there any cleaner way to achieve ?

2

Answers


  1. U can try the following code.

    let input = "boolFirst=false|onProject=Active|passed=false"
    
    var output: [String: Any] = [:]
    
    let pairs = input.components(separatedBy: "|")
    for pair in pairs {
        let components = pair.components(separatedBy: "=")
        let key = components[0]
        
        if components[1] == "true" {
            output[key] = true
        } else if components[1] == "false" {
            output[key] = false
        } else {
            output[key] = components[1]
        }
    }
    
    print(output)
    

    Output Printed —

    ["onProject": "Active", "passed": false, "boolFirst": false]
    
    Login or Signup to reply.
  2. We can use the swift Regex and RegexBuilder functionality for this.

    The regex would be

    let regex = Regex {
            Capture {
                OneOrMore(.word)
            } transform: { substring in
                String(substring)
            }
            "="
            Capture  {
                OneOrMore(.any)
            }
        Optionally {
            "|"
        }
    }
    

    and then convert the result of matching the regex to a dictionary by using reduce(into:)

    let output = input.matches(of: regex)
        .reduce(into: [String:Any]()) { $0[$1.output.1] = $1.output.2 }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search