Athila Zuma Athila Zuma - 1 month ago 12
iOS Question

converting function in Objective-C to swift

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)?

Answer

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 self.componentsSeparatedByCharactersInSet(.controlCharacterSet())
                   .joinWithSeparator("")
    }
}