Apple 的 Swift documentation指出
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
如果我有一个 String 对象,例如
var newString: String = "this is a string"
如何在我的字符串变量上执行像 containsString
这样的 NSString 操作?
最佳答案
经过一些研究,看起来 containsString
不是一个 String
函数,但可以通过桥接到一个 NSString
来访问。
根据 Apple 文档 Using Swift with Cocoa and Objective-C , 它说
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
但似乎只有 NSString 的一些功能可以在没有显式桥接的情况下访问。要桥接到 NSString 并使用它的任何功能,可以使用以下方法:
//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")
所有这三个都有效。
有趣的是,只有一些 NSString
方法可用于 Strings
,而其他方法则需要显式桥接。这可能是随着 Swift 的发展而构建的。
关于nsstring - 在 Swift 中的字符串上调用 NSString 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24006549/