Reputation: 1675
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?
Upvotes: 4
Views: 2684
Reputation: 1396
In more general cases, collectionType.indexOf
will work when the object inside an array conforms to Equatable
protocol. Since Swift String
has already conformed to Equatable
, then casts AnyObject
to String
will remove the error.
How to use indexOf
on collection type custom class ? Swift 2.3
class Student{
let studentId: Int
let name: String
init(studentId: Int, name: String){
self.studentId = studentId
self.name = name
}
}
//notice you should implement this on a global scope
extension Student: Equatable{
}
func ==(lhs: Student, rhs: Student) -> Bool {
return lhs.studentId == rhs.studentId //the indexOf will compare the elements based on this
}
func !=(lhs: Student, rhs: Student) -> Bool {
return !(lhs == rhs)
}
Now you can use it like this
let john = Student(1, "John")
let kate = Student(2, "Kate")
let students: [Student] = [john, kate]
print(students.indexOf(John)) //0
print(students.indexOf(Kate)) //1
Upvotes: 0
Reputation: 3433
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("")
Upvotes: 6
Reputation: 14973
You should never use AnyObject
for a placeholder for any type, use Any
instead. Reason: AnyObject
only works with classes, Swift uses a lot of structs though (Array, Int, String, etc.). Your code actually uses NSString
s instead of Swifts native String
type because AnyObject
wants a class (NSString
is a class).
Upvotes: 0
Reputation: 6669
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("")
Upvotes: 3