gpt4 book ai didi

ios - 如何将 Swift String 桥接到 Objective C NSString?

转载 作者:IT王子 更新时间:2023-10-29 05:20:28 25 4
gpt4 key购买 nike

我是在吃疯狂的药吗?直接出文档:

“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.

要启用字符串桥接,只需导入 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)

我错过了什么吗?

最佳答案

要从 StringNSString 使用以下构造函数:

let swiftString:String = "I'm a string."
let objCString:NSString = NSString(string:swiftString)

在 Xcode 7(测试版) 中,使用从 StringNSString 的向下转型,如下例所示,将产生一条警告消息, 从 'String' 中转换?到不相关的类型“NSString”总是失败:

let objcString:NSString = swiftString as! NSString // results in error

关于ios - 如何将 Swift String 桥接到 Objective C NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28567725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com