Search code examples
arraysswiftswift3swift-string

How to convert Strings in Swift?


I've two cases where I need to convert strings to different formats.

for ex:

case 1:
  string inputs: abc, xyz, mno, & llr   // All Strings from a dictionary
  output: ["abc","xyz", "mno", "llr"]  //I need to get the String array like this.

But when I use this code:

 var stringBuilder:[String] = [];
 for i in 0..<4 {
   stringBuilder.append("abc"); //Appends all four Strings from a Dictionary
 }

print(stringBuilder); //Output is 0: abc, 1:xyz like that, how to get desired format of that array like ["abc", "xyz"];

Real usage:

let arr = Array(stringReturn.values);
//print(arr)  // Great, it prints ["abc","xyz"];
let context = JSContext()
context?.evaluateScript(stringBuilder)   
let testFunction = context?.objectForKeyedSubscript("KK")
let result = testFunction?.call(withArguments:arr); // Here when I debugger enabled array is passed to call() like 0:"abc" 1:"xyz". where as it should be passed as above print.

Secondly how to replace escape chars in swift: I used "\" in replaceOccurances(of:"\\'" with:"'"); but its unchanged. why and how to escape that sequnce.

case 2:
  string input: \'abc\'
  output: 'abc'

Solution

  • To get all values of your dictionary as an array you can use the values property of the dictionary:

    let dictionary: Dictionary<String, Any> = [
        "key_a": "value_a",
        "key_b": "value_b",
        "key_c": "value_c",
        "key_d": "value_d",
        "key_e": 3
    ]
    
    let values = Array(dictionary.values)
    // values: ["value_a", "value_b", "value_c", "value_d", 3]
    

    With filter you can ignore all values of your dictionary that are not of type String:

    let stringValues = values.filter({ $0 is String }) as! [String]
    // stringValues: ["value_a", "value_b", "value_c", "value_d"]
    

    With map you can transform the values of stringValues and apply your replacingOccurrences function:

    let adjustedValues = stringValues.map({ $0.replacingOccurrences(of: "value_", with: "") })
    // adjustedValues: ["a", "b", "c", "d"]