18

I have variable which contents the symbol or character I don't know how you say on this "\" in english... How to replace all \ with empty space in my variable ?

var content = theContent["content"] as String
self.contentLabel.text = content.stringByReplacingOccurrencesOfString(<#target: String#>, withString: <#String#>, options: <#NSStringCompareOptions#>, range: <#Range<String.Index>?#>)

How to fill this spaces or my sintax is wrong when I use content.string... and then in #target I use the same string ? Anyone who learned Swift so fast? :D

Ashish Kakkad
  • 23,020
  • 11
  • 96
  • 132
Bogdan Bogdanov
  • 1,182
  • 11
  • 35
  • 72

2 Answers2

28

Use the following

self.contentLabel.text = content.stringByReplacingOccurrencesOfString("\\", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil)
nicael
  • 17,612
  • 12
  • 55
  • 87
14

If you want to write this in pure Swift, try:

self.contentLabel.text = Array(myString).reduce("") { $1 == "\\" ? $0 : "\($0)\($1)" }

This is a short hand way of writing:

Array(myString).reduce("", combine: { (inputString, character) -> String in
    if character == "\\" {
        return inputString
    } else {
        return "\(inputString)\(character)"
    }
})

This converts myString to an Array of Characters, then uses the reduce function to append them back together into a String, but substituting an empty string in place of backslashes

Ashley Mills
  • 44,005
  • 15
  • 120
  • 151
  • What do you mean pure swift? This looks intense. Can you explain whats going on in this example? – Aggressor Mar 26 '15 at 19:51
  • 3
    By *pure* Swift, I mean that it doesn't use any Foundation classes (NSString, for example) - updated my answer for clarity – Ashley Mills Mar 27 '15 at 13:53