swiftstring

Swift - Remove " character from string


I have a string which is "Optional("5")". I need to remove the "" surrounding the 5. I have removed the Optional by doing:

text2 = text2.stringByReplacingOccurrencesOfString("Optional(", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

I am having difficulties removing the " characters as they designate the end of a string in the code.


Solution

  • Swift uses backslash to escape double quotes. Here is the list of escaped special characters in Swift:

    • \0 (null character)
    • \\ (backslash)
    • \t (horizontal tab)
    • \n (line feed)
    • \r (carriage return)
    • \" (double quote)
    • \' (single quote)

    This should work:

    text2 = text2.replacingOccurrences(of: "\\", with: "", options: NSString.CompareOptions.literal, range: nil)