Search code examples
iosarraysswiftany

Swift 3 array indexOf function is missing


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


}

Solution

  • 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"))")