Calling NSString method on a String in Swift

nsstring, swift

Solution

After doing some research, it looks like `containsString` is not a `String` function, but can be accessed by bridging to an `NSString`.

Under Apple's Documentation on Using Swift with Cocoa and Objective-C, it says that

Swift automatically bridges between the String type and the NSString class. This means that anywhere you use an NSString object, you can use a Swift String type instead and gain the benefits of both types

But it appears that only some of NSString's functions are accessible without explicitly bridging. To bridge to an NSString and use any of its functions, the following methods work:

 //Example Swift String var
    var newString:String = "this is a string"

    //Bridging to NSString
    //1
    (newString as NSString).containsString("string")
    //2
    newString.bridgeToObjectiveC().containsString("string")
    //3
    NSString(string: newString).containsString("string")

All three of these work. It's interesting to see that only some `NSString` methods are available to `Strings` and others need explicit bridging. This may be something that is built upon as Swift develops.

Problem

Apple's Swift documentation states that If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create If I have a String object eg ``` var newString: String = "this is a string" ``` How do I perform NSString operations like `containsString` on my String var?

Original source