Reputation: 391
I'm trying to remove unescaped control character of a json, I could already converts it to String, but now I'm trying to adapt this function in Objective-C for swift.
- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
if (range.location != NSNotFound) {
NSMutableString *mutable = [NSMutableString stringWithString:inputString];
while (range.location != NSNotFound) {
[mutable deleteCharactersInRange:range];
range = [mutable rangeOfCharacterFromSet:controlChars];
}
return mutable;
}
return inputString;
}
Following this as reference: Unescaped control characters in NSJSONSerialization
I got it but does not work:
func stringByRemovingControlCharacters(inputString: String) -> String {
var controlChars = NSCharacterSet.controlCharacterSet<NSObject>()
var range = inputString.rangeOfCharacterFromSet<NSObject>(controlChars)
if range.location != NSNotFound {
var mutable = String = inputString
while range.location != NSNotFound {
mutable.deleteCharactersInRange(range)
range = mutable.rangeOfCharacterFromSet<NSObject>(controlChars)
}
return mutable
}
return inputString
}
Cannot explicitly specialize a generic function
Cannot assign to immutable expression of type 'String.Type'
How could adapt it appropriately for swift (Swift 2.3)?
Upvotes: 1
Views: 252
Reputation: 7582
The closest you can get to the code you provide is the following:
func stringByRemovingControlCharacters(string: String) -> String {
let controlChars = NSCharacterSet.controlCharacterSet()
var range = string.rangeOfCharacterFromSet(controlChars)
var mutable = string
while let removeRange = range {
mutable.removeRange(removeRange)
range = mutable.rangeOfCharacterFromSet(controlChars)
}
return mutable
}
Though I do not recommend you use the code above.
You can write it in a more Swifty
way like this:
func stringByRemovingControlCharacters(string: String) -> String {
return string.componentsSeparatedByCharactersInSet(.controlCharacterSet())
.joinWithSeparator("")
}
or even as an extension:
extension String {
func stringByRemovingControlCharacters() -> String {
return componentsSeparatedByCharactersInSet(.controlCharacterSet())
.joinWithSeparator("")
}
}
For completion sake:
extension String {
var removingControlCharacters: String {
return components(separatedBy: .controlCharacters).joined()
}
}
Upvotes: 4