This works
let replaced = String(map(aString.generate()) {
$0 == " " ? "-" : $0 })
and this doesn't
let replaced = String(map(aString.generate()) {
$0 == " " ? "" : $0 })
Why?
This works
let replaced = String(map(aString.generate()) {
$0 == " " ? "-" : $0 })
and this doesn't
let replaced = String(map(aString.generate()) {
$0 == " " ? "" : $0 })
Why?
For Swift 5:
" spaces here ".replacingOccurrences(of: " ", with: "")
returns:
"spaceshere"
Enumerating a string gives a sequence of characters, so $0 inside
the closure has the type Character. This compiles
{ $0 == " " ? "-" : $0 }
because "-" in this context is interpreted as a character literal
and therefore of the same type as $0. But
{ $0 == " " ? "" : $0 }
does not compile because "" is not a character literal (and in the conditional expression a ? b : c the operands b and c
must have the same type).
You can fix that by converting $0 to a string:
{ $0 == " " ? "" : String($0) }
but now the mapping returns an array of strings instead
of an array of characters. So instead
of the String() constructor you have to join the results:
let replaced = "".join(map(aString) { $0 == " " ? "" : String($0) })
// Swift 2 / Xcode 7:
let replaced = "".join(aString.characters.map({ $0 == " " ? "" : String($0) }))
(Note that calling generate() explicitly is not needed.)
Of course the same result would also be achieved with
// Before Swift 3.0
let replaced = aString.stringByReplacingOccurrencesOfString(" ", withString: "")
// After Swift 3.0
let replaced = aString.replacingOccurrences(of: " ", with: "")
If you want to remove white space from string then just pass string with stringByReplacingOccurrencesOfString function like below,
let replacedString = string.replacingOccurrences(of: " ", with: "")
For Text Fields, you can apply directly object of UITextField,
let replacedString = textField.text!.replacingOccurrences(of: " ", with: "")
This should work as of Swift 2.2:
let replaced = String(aString.characters.filter {$0 != " "})
If you want to delete whitespaces before and after a string, which is very useful in user input forms, you can use:
let replaced = aString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
You can apply it directly on a textfield as well.
If you want to remove all whitespaces anywhere in the String I did come up with this solution for Swift 3.0:
let number = "+000 000 000"
let nonWhiteCharacters = number.unicodeScalars.filter {
false == NSCharacterSet.whitespacesAndNewlines.contains($0)
}.map(Character.init)
let whitespacelessNumber = String(nonWhiteCharacters)
or even better (you will need generic extension on Sequence):
extension Sequence {
public func reduce<Result>(_ result: (Self) throws -> Result) rethrows -> Result {
return try result(self)
}
}
and then you can write:
let whitespacelessNumber = number.unicodeScalars.filter {
false == NSCharacterSet.whitespacesAndNewlines.contains($0)
}.map(Character.init).reduce { String($0) }
where you can also replace NSCharacterSet.whitespacesAndNewlines for any of other character sets:
NSCharacterSet.controlCharacters
NSCharacterSet.whitespaces
NSCharacterSet.whitespacesAndNewlines
NSCharacterSet.decimalDigits
NSCharacterSet.letters
NSCharacterSet.lowercaseLetters
NSCharacterSet.uppercaseLetters
NSCharacterSet.nonBaseCharacters
NSCharacterSet.alphanumerics
NSCharacterSet.decomposables
NSCharacterSet.illegalCharacters
NSCharacterSet.punctuationCharacters
NSCharacterSet.capitalizedLetters
NSCharacterSet.symbols
NSCharacterSet.newline
You are mapping thus the number of elements should be preserved. In the second case you remove elements. Your example will fail even in case you replace " " with --.
You might prefer using filter:
let replaced = String(filter(aString.generate()) { $0 != " "})
try this one:
let strArray0 = strArray1.map { $0.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) }
Hope this helps
None of the previous answers where Swifty enough for me, so I ended up with this using Swift 5:
let nonWhitespaceString = String(whitespaceString.compactMap({ $0.isWhitespace ? nil : $0 })
In Swift 3.0 DO as
func RemoveWhiteSpace(aString:String) -> String
{
let replaced = aString.trimmingCharacters(in: NSCharacterSet.whitespaces)
return replaced
}
And use like this
let nonWhiteSpaceStr = self.RemoveWhiteSpace(aString: "I have white Space ")