Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling NSString method on a String in Swift

Tags:

swift

nsstring

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?

like image 489
Jpoliachik Avatar asked Jun 03 '14 03:06

Jpoliachik


2 Answers

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.

like image 188
Jpoliachik Avatar answered Sep 17 '22 16:09

Jpoliachik


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") 
like image 38
Connor Avatar answered Sep 21 '22 16:09

Connor