How to bridge Swift String to Objective C NSString?

前端 未结 3 2346
我寻月下人不归
我寻月下人不归 2021-02-13 10:12

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

“Swift automatically bridges between the String type and the NSString class. This means that

相关标签:
3条回答
  • 2021-02-13 10:17

    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);
    
    0 讨论(0)
  • 2021-02-13 10:22

    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
    
    0 讨论(0)
  • 2021-02-13 10:32

    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.

    0 讨论(0)
提交回复
热议问题