stringByReplacingOccurrencesOfString is not working?
objective-c, swift
Solution
Keep in mind that Foundation's types are different from Swift's types. A `String` in Swift is not an `NSString`, and a `Range` is not an `NSRange`. This does work:
let country = self.appStoreCountry // if self.appStoreCountry is an NSString
let country: NSString = self.appStoreCountry // if self.appStoreCountry is a Swift string
let replaced = country.stringByReplacingOccurrencesOfString("[A-Za-z]{2}", withString: "", options: .RegularExpressionSearch, range: NSMakeRange(0, 2))
Also note the short-hand notation for `.RegularExpressionSearch`, which makes using enums in Swift a bit easier.
Problem
I am trying to translate this Objective-C code : ``` if ([[self.appStoreCountry stringByReplacingOccurrencesOfString:@"[A-Za-z]{2}" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, 2)] length]) ``` So I tried to wrote this code : ``` if !self.appStoreCountry.stringByReplacingOccurrencesOfString("[A-Za-z]{2}", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: 0, end: 2)).isEmpty ``` The problem is that the stringByReplacingOccurrencesOfString part does not seem to return a string. I have the error message from xcode : `Cannot convert the expression's type 'Bool' to type 'String'.` I investigated a little more and tried : ``` let replaced = self.appStoreCountry.stringByReplacingOccurrencesOfString("[A-Za-z]{2}", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: Range(start: 0, end: 2)) ``` The error message is similar but even more weird : `Cannot convert the expression's type 'String' to type 'String'.` Am I doing something wrong or is there a bug I should submit to Apple?