加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中的String上调用NSString方法

发布时间:2020-12-14 06:01:35 所属栏目:百科 来源:网络整理
导读:苹果的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对象eg var newString: String = "this is a st
苹果的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对象eg

var newString: String = "this is a string"

我如何执行NSString操作,如我的String var的containsString?

经过一些研究,看起来containsString不是一个String函数,但可以通过桥接到一个NSString访问。

在苹果的文档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开发的基础。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读