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?
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.
The methods are the same, but they just use swift's syntax instead. For example:
var newString: String = "this is a string" newString = newString.stringByAppendingString(" that is now longer") println(newString)
instead of:
NSString* newString = @"this is a string"; newString = [newString stringByAppendingString:@" that is now longer"]; NSLog(newString);
Note:
Not all of NSString's methods can be called on String. Some you have to bridge to NSString first like so:
newString.bridgeToObjectiveC().containsString("string")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With