Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexOf of AnyObject array not working with Strings

So I'm having the following code in a playgroung

var array: [AnyObject] = ["", "2", "3"]

let index = array.indexOf("")

And XCode is marking a compiler error

Cannot convert value of type 'String' to expected argument type '@noescape (AnyObject) throws -> Bool'

So my question is how do I get the indexOf an element in an Array in of AnyObjects?

like image 377
Black Sheep Avatar asked Jan 08 '23 10:01

Black Sheep


2 Answers

You can also cast to [String] if you're sure it will cast safely

jvar array: [AnyObject] = ["", "2", "3"]
let index = (array as! [String]).indexOf("")
like image 181
Lukas Avatar answered Jan 14 '23 19:01

Lukas


Try this

var array = ["", "2", "3"]
let index = array.indexOf("")

or you can use the NSArray method:

var array: [AnyObject] = ["", "2", "3"]
let index = (array as NSArray).indexOfObject("")
like image 29
Marius Fanu Avatar answered Jan 14 '23 21:01

Marius Fanu