在 Swift 中对字符串调用 NSString 方法 [英] Calling NSString method on a String in Swift

查看:81
本文介绍了在 Swift 中对字符串调用 NSString 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple 的 Swift 文档指出

Apple's Swift documentation states that

如果您在 Cocoa 或 Cocoa Touch 中使用 Foundation 框架,则整个 NSString API 可用于调用您创建的任何 String 值

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 对象,例如

If I have a String object eg

var newString: String = "this is a string"

如何在我的 String var 上执行像 containsString 这样的 NSString 操作?

How do I perform NSString operations like containsString on my String var?

推荐答案

经过一番研究,看起来containsString不是String函数,而是可以访问通过桥接到 NSString.

After doing some research, it looks like containsString is not a String function, but can be accessed by bridging to an NSString.

将 Swift 与 Cocoa 和 Objective-C 结合使用的 Apple 文档下,它说

Swift 自动桥接 String 类型和 NSString班级.这意味着在任何使用 NSString 对象的地方,您都可以改用 Swift String 类型并获得两种类型的好处

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 并使用其任何功能,请使用以下方法:

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

这三个都有效.有趣的是,只有一些 NSString 方法可用于 Strings,而其他方法需要显式桥接.这可能是随着 Swift 的发展而构建的.

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.

这篇关于在 Swift 中对字符串调用 NSString 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆