Calling NSString method on a String in Swift

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
    (newString as NSString).containsString("string")
    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.

Leave a Comment