15
votes

Am I taking crazy pills? Directly out of the documentation:

“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—the String type’s interpolation and Swift-designed APIs and the NSString class’s broad functionality. For this reason, you should almost never need to use the NSString class directly in your own code. In fact, when Swift imports Objective-C APIs, it replaces all of the NSString types with String types. When your Objective-C code uses a Swift class, the importer replaces all of the String types with NSString in imported API.

To enable string bridging, just import Foundation.”

I've done this... consider:

import Foundation

var str = "Hello World"

var range = str.rangeOfString("e")

// returns error: String does not contain member named: rangeOfString()

However:

var str = "Hello World" as NSString

var range = str.rangeOfString("e")

// returns correct (2, 1)

Am I missing something?

3
Actually the first case shouldn't return an error. It should be {Some "1..<2"} - Leo Dabus
The second one should return (1,1) - Leo Dabus
Im not making it up... It will not work - Bren
Your right it does return (1,1) :-) However I guess I am not understanding the point of needing to cast it to NSString. - Bren
Which Xcode versions are you using? Both your code samples compile in Xcode 6.1.1 and in 6.3 beta. - Martin R

3 Answers

32
votes

To go from String to NSString use the following constructor:

let swiftString:String = "I'm a string."
let objCString:NSString = NSString(string:swiftString)

With Xcode 7 (beta), using a downcast from String to NSString, as in below example, will result in a warning message, Cast from 'String?' to unrelated type 'NSString' always fails:

let objcString:NSString = swiftString as! NSString // results in error
9
votes

You already have the answer in your question. You're missing the cast. When writing Swift code, a statement such as this one

var str = "Hello World"

creates a Swift String, not an NSString. To make it work as an NSString, you should cast it to an NSString using the as operator before using it.

This is different than calling a method written in Objective-C and supplying a String instead of an NSString as a parameter.

-1
votes

Here is example for this :

string str_simple = "HELLO WORLD";

//string to NSString
NSString *stringinObjC = [NSString stringWithCString:str_simple.c_str()
                                encoding:[NSString defaultCStringEncoding]];            
NSLog(stringinObjC);