【问题标题】:Why is Xcode not recognizing indexOfObjectIdenticalTo in swift array?为什么 Xcode 不能识别 swift 数组中的 indexOfObjectIdenticalTo?
【发布时间】:2020-03-25 20:03:57
【问题描述】:

我正在尝试翻译一些 Objective-C 代码:

NSArray *containers = [layoutManager textContainers];
NSUInteger lastUsedContainerIndex = [containers indexOfObjectIdenticalTo:textContainer];

到斯威夫特:

let textContainers = layoutManager.textContainers
let lastUsedContainerIndex = textContainers.indexOfObjectIdentical(to: textContainers)

其中 layoutManager 是 NSLayoutManager 类型。我在 Swift 代码的最后一行收到此错误:

“[NSTextContainer]”类型的值没有成员 'indexOfObjectIdenticalTo'

不明白这一点。我已经在文档中搜索了 Swift 并且 NSArray 有 indexOfObjectIdenticalTo 但它没有出现在 Xcode 的自动完成中并且给了我这个错误。是 Swift 的新手,想知道我在这里缺少什么?

【问题讨论】:

  • 在 Swift 中,这被导入为NSArray.indexOfObjectIdentical(to:),所以这将被拼写为:textContainers.indexOfObjectIdentical(to: textContainers)。但在 Swift 中,这会更传统地写成:textContainers.firstIndex(where: { $0 === textContainers })

标签: ios swift xcode macos nsarray


【解决方案1】:

在 Swift 中,这被导入为 Foundation.NSArray.indexOfObjectIdentical(to:)。这在Swift.Array 上不可用,因此您首先必须将您的Array 桥接到NSArray,所以这将是拼写:

let textContainers = layoutManager.textContainers
let lastUsedContainerIndex = NSArray(textContainers).indexOfObjectIdentical(to: textContainer)

但在 Swift 中,这会更传统地写成:

let textContainers = layoutManager.textContainers
let lastUsedContainerIndex = textContainers.firstIndex(where: { $0 === textContainer })

【讨论】:

  • 非常感谢,当我看到文档如何进行 Swift 翻译时,我对 NSArray 和 Swift 数组之间的区别感到困惑,认为它们是相同的(可能隐含在 Swift 中)。跨度>
  • @NSMoron TL;DR:Swift 的原生数组类型是Array。 NSArray 是 Foundation 的一部分,可用于 Swift 以支持与旧的 ObjC API 的互操作性。大多数 ObjC API(如 UIKit)已被注释为使用 Array 桥接到 Swift,但不是全部。
  • 现在说得通了,感谢您花时间解释它。
【解决方案2】:

[NSTextContainer] 不是NSArray 的实例。您可以尝试将您的数组转换为NSArray。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2010-10-19
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多