nsstring - 在 Swift 中的字符串上调用 NSString 方法

标签 nsstring swift

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/

相关文章:

arrays - NSString 到数组整数 Swift Xcode

iphone - 如何检查 NSString 是否包含数值?

ios - Pinterest IOS SDK getBoardPins 响应代码=-1011 "Request failed: bad request (400)"

swift - 从父类(super class)调用所有子类的函数

Swift:为什么 init?(length length: Int) NSMutableData 的初始化程序会失败?

ios - Swift:UIView.animate 工作意外

objective-c - 使用格式说明符声明一个 NSString 并将其用作在 UIWebview 中打开的 URL

iphone - 如何使用NSDateFormatter将NSString转换为NSDate?

ios - 自定义segue到同级 View Controller

ios - Base64 解码 NSString 的异常结果