如何将Swift String桥接到Objective C NSString? [英] How to bridge Swift String to Objective C NSString?

查看:230
本文介绍了如何将Swift String桥接到Objective C NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我服用疯狂的药吗?直接来自文档:

Am I taking crazy pills? Directly out of the documentation:


Swift自动在String类型和NSString类之间架起桥梁。这意味着在使用NSString对象的任何地方,您都可以使用Swift String类型,并获得两种类型的好处 - String类型的插值和Swift设计的API以及NSString类的广泛功能。因此,您几乎不需要在自己的代码中直接使用NSString类。实际上,当Swift导入Objective-C API时,它会用String类型替换所有NSString类型。当您的Objective-C代码使用Swift类时,导入器会在导入的API中使用NSString替换所有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—the String type’s interpolation and Swift-designed APIs and the NSString class’s broad functionality. For this reason, you should almost never need to use the NSString class directly in your own code. In fact, when Swift imports Objective-C APIs, it replaces all of the NSString types with String types. When your Objective-C code uses a Swift class, the importer replaces all of the String types with NSString in imported API.

启用字符串桥接,只需导入基础。

To enable string bridging, just import Foundation."

我做到了这一点......考虑:

import Foundation

var str = "Hello World"

var range = str.rangeOfString("e")

// returns error: String does not contain member named: rangeOfString()

但是:

var str = "Hello World" as NSString

var range = str.rangeOfString("e")

// returns correct (2, 1)

我错过了什么吗?

推荐答案

您已经在问题中找到了答案。你错过了演员。在编写Swift代码时,这样的语句

You already have the answer in your question. You're missing the cast. When writing Swift code, a statement such as this one

var str = "Hello World"

创建一个Swift String ,而不是 NSString 。要使其作为 NSString 工作,您应该使用将其转换为 NSString 运算符在使用之前。

creates a Swift String, not an NSString. To make it work as an NSString, you should cast it to an NSString using the as operator before using it.

这与调用Objective-C编写的方法并提供 String <不同/ code>而不是 NSString 作为参数。

This is different than calling a method written in Objective-C and supplying a String instead of an NSString as a parameter.

这篇关于如何将Swift String桥接到Objective C NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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