Calling NSString method on a String in Swift

非 Y 不嫁゛ 提交于 2019-11-29 16:01:09

问题


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?


回答1:


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.




回答2:


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")



回答3:


So what you actually have to do is this

var str:NSString = "Checkcontains"
str.containsString("ckc")

Notice how the declaration of an explicit NSString is put there. Then you can use the containsString method. If you only use var and do not set it as an NSString then you have problems.




回答4:


You can call any NSString method on a Swift String object; under the hood, the two objects are 'toll-free bridged'. Thus, you can just do:

var newString = "this is a string"
if newString.containsString("string") {
    //do your stuff
}


来源:https://stackoverflow.com/questions/24006549/calling-nsstring-method-on-a-string-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!