NSMoron
NSMoron

Reputation: 151

Why is Xcode not recognizing indexOfObjectIdenticalTo in swift array?

I'm trying to translate some Objective-C code:

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

to Swift:

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

Where layoutManager is of type NSLayoutManager. I'm getting this error on the last line of the Swift code:

Value of type '[NSTextContainer]' has no member 'indexOfObjectIdenticalTo'

Not understanding this. I've searched the docs for Swift and NSArray has indexOfObjectIdenticalTo yet it's not showing up in Xcode's autocomplete and is giving me this error. Am new to Swift so wondering what am I missing here?

Upvotes: 0

Views: 153

Answers (2)

Alexander
Alexander

Reputation: 63321

In Swift, this is imported as Foundation.NSArray.indexOfObjectIdentical(to:). This isn't available on Swift.Array, so you would first have to bridge your Array to NSArray, so this would be spelt:

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

But in Swift, this would be more conventionally written as:

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

Upvotes: 1

dasdom
dasdom

Reputation: 14073

[NSTextContainer] is not an instance of NSArray. You could try to cast your array to NSArray.

Upvotes: 1

Related Questions