0

I am trying to split this string to an array, I will later convert this array to a dictionary

let string = "test=1&name=Noodle&item=100"
let edit = string.components(separatedBy: "=")
// string.components(separatedBy: "=" && "&")???

But this only separate the string by one character, which is "="

What I am trying to achieve is to separate the string with two character, "=" and "&". How can I achieve that?

0

2 Answers 2

2

what you can do is you can replace occurence of characters in string and than you can separate it

let string = "test=1&name=Noodle&item=100"

let edit = string.replacingOccurrences(of: "&", with: "=").components(separatedBy: "=")
Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm! How can I didn't think about this...
thanks happy to help
2

You can do it like so:

func stringConvert(string: String) -> [String: Any] {

    let keysAndValues = string.components(separatedBy: "&")
    let arraysOfPairs = keysAndValues.map { $0.components(separatedBy: "=") }
    let tuples = arraysOfPairs.map { ($0[0], $0[1]) }
    let d = Dictionary(uniqueKeysWithValues: tuples)

    return d
}

let str = "test=1&name=Noodle&item=100"

let dict = stringConvert(string: str)
//["test": "1", "item": "100", "name": "Noodle"]

6 Comments

there's an error in the "let d" line that says "argument label 'unique KeysWithValues' do not match any available overloads"
@Nodoodle Are you using Swift 4.2 ?
yes, I am using 4.2
@Nodoodle because that function is part of the standard library. Do try it in a playground (don't forget import Foundation)
still have the same error. But I found the answer here stackoverflow.com/questions/43118687/split-url-query-in-swift . But this one isn't dynamic
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.