Sanket Bhavsar Sanket Bhavsar - 1 year ago 161
Objective-C Question

Objective C code in Swift 3.0

I have been trying to convert a piece of code from Objective C to Swift 3.0 syntax with no success. Please find the objective c code below.

Objective C

NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "] invertedSet];

NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];

Here's what I have tried,

Swift 3.0

let invalidCharSet : NSCharacterSet = NSCharacterSet.init(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").inverted as NSCharacterSet

let filtered = (replacementString.components(separatedBy: invalidCharSet)as NSArray).componentsJoined(by: "")

The second statement(i.e. filtered = ..) giving the following error,


'components' produces '[String]', not the expected contextual result
type 'NSArray'

Answer Source

Don't use NSArray, use a Swift array and call .joined on it. As a general rule, in Swift, try to avoid using Foundation, better use Swift's own typed tools.

let invalidCharSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").inverted

let filtered = replacementString.components(separatedBy: invalidCharSet).joined(separator: " ")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download