henry henry - 3 years ago 138
Swift Question

Separate a string in Swift

How can I get the value after the colon?

Example string: "aaa:test , bbb:test , ccc:test"

I would have to recognize aaa:, bbb:, ccc: to get the value after the colon.

There's also a special case: "aaa:aaa: , bbb:bbb, , ccc:test"

The value may or may not have exactly the same word as the variable. Also, the value may contain a comma.

Answer Source

Use componenetSeparatedBy method of String. I am assuming that all the key-value will be separated by " , "

   let wordsArr = "aaa:test: , bbb:test,a , ccc:test".components(separatedBy: " , ") as [String]

This will give you an array with words {[aaa:test:] , [ bbb:test,a] , [ccc:test]}

    var aaa, bbb, ccc : String?

    for (_,keyValueWords) in wordsArr.enumerated()  {

        var strKeyValuePair = keyValueWords
        if strKeyValuePair.hasPrefix("aaa:") {
            aaa = String(strKeyValuePair.characters.dropFirst(4))
        else if strKeyValuePair.hasPrefix("bbb:"){
            bbb = String(strKeyValuePair.characters.dropFirst(4))

        }else  if strKeyValuePair.hasPrefix("ccc:"){
            ccc = String(strKeyValuePair.characters.dropFirst(4))


    print("aaa=\(aaa!) , bbb=\(bbb!) , ccc=\(ccc!)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download