String

conversion

A common task is to convert a string to other types and vice versa.

// any value to String
let str = "\(someValue)"
// Data to String
let str = String(decoding: data, as: UTF8.self)
let str = String(myIntValue) // same with others

extension Data {
    func toString() -> String {
        return String(decoding: self, as: UTF8.self)
    }
}

iterate over characters

for ch in str {
  // ...
}

str.forEach { ch in
  
}

for (ind, ch) in str.enumerated() {
   
}

split string

var components = str.components(separatedBy: ",")

let separators = CharacterSet(charactersIn: "-+")
components = str.components(separatedBy: separators)

remove characters

// remove character at given position
var newStr = string.remove(at: i) 

newStr = str.replacingOccurrences(of: "search_string", 
                                      with: "replacement",  // "" for removing
                                      options: NSString.CompareOptions.literal,
                                      range: nil)

newStr = str.replacingOccurrences(of: "[abc]", 
                                  with: "", 
                                  options: [.regularExpression, .caseInsensitive]
                                  )

// remove leading and trailing characters
newStr =  trimmingCharacters(in: ["(",")"])