0

I have an array of UIViewController in my protocol

var viewControllers: [MyViewController] { get }

I want to get the index of item with specific ViewController

let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController)

But the type of idfx is Array.index.

How can I get the index of an array element as an Int?

2 Answers 2

7

The problem isn't that it's of type Array.index, which is a typealias for Int, as Nonuld says. The problem is that it's an optional. You need to unwrap the optional somehow. One way is to use "if let" optional binding:

if let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController) {
  print("view controller found at index \(idfx)") 
} else {
  print("View controller not found in array")
}
Sign up to request clarification or add additional context in comments.

Comments

3

Actually the type Array.Index is a typealias to the type Int, so you can do the same operation as if you had an integer with the result of the method index(of:).

1 Comment

Beware: this answer ignores the fact the question assumption "But the type of idfx is Array.index" is false. The returned type is optional, see the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.