4

When I try to print index of the array which contains any object. It's not suggesting the indexOf function. When I try to enter manually its shows error that I have attached screenshot.

But it's working for Array of String. Can anyone please help me to solve this?

enter image description here

Also Here I am showing my code

import UIKit

class ViewController: UIViewController {

    var arrayOfAnyObject: [Any] = [Any]()
    var arrayOfStringObject: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()


         print("Index of string object array \(arrayOfStringObject.index(of: "anyString")!)")

         print("Index of any object array \(arrayOfAnyObject.index(of: "anyObject")!)")




        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
Mani murugan
  • 1,792
  • 2
  • 17
  • 32

1 Answers1

4

You could either set the type that you need in the array (Int, String etc..) or convert the arrayOfAnyObject to AnyObject before you do the indexOf, like this:

print("Index of any object array \((arrayOfAnyObject as AnyObject).index(of: "anyObject"))")
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • Thanks Rashwan. Its working. Can you please tell me why Its not showing indexOF function without convert. Anyway Its a array Right ? – Mani murugan Jun 08 '17 at 06:16
  • 1
    @Manimurugan, great. It doe not work because `Any` does not confirm to the equatable protocol. Read more [here](https://developer.apple.com/documentation/swift/equatable). – Rashwan L Jun 08 '17 at 06:20
  • @Manimurugan.mine is not working here. why :( i just changed my data type to AnyObject what Rashwan advised. like this var arrayOfAnyObject: [AnyObject] = [AnyObject]() – elk_cloner Jun 08 '17 at 06:32
  • 1
    @elk_cloner, keep your array as `Any` and when you do the `indexOf` use the example I provided. – Rashwan L Jun 08 '17 at 06:33