Reputation: 745
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,
Error
'components' produces '[String]', not the expected contextual result type 'NSArray'
Upvotes: 2
Views: 603
Reputation: 70098
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: " ")
Upvotes: 3