IndexOf array of AnyObject not working with strings

So I have the following code in playgroung

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

let index = array.indexOf("")

And Xcode notes a compiler error

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

So my question is: how can I get the indexOf element in an array from AnyObjects?

+4
source share
4 answers

You can also use for [String] if you are sure that it will display safely

jvar array: [AnyObject] = ["", "2", "3"]
let index = (array as! [String]).indexOf("")
+6
source

try it

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

or you can use the method NSArray:

var array: [AnyObject] = ["", "2", "3"]
let index = (array as NSArray).indexOfObject("")
+3
source

AnyObject , Any. : AnyObject , Swift (Array, Int, String ..). NSString String Swifts, AnyObject (NSString - ).

0

In more general cases, it collectionType.indexOfwill work if the object inside the array matches the protocol Equatable. Since Swift Stringalready matches Equatable, it drops AnyObjectto String.

How to use a indexOfcollection type in a 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
0
source

Source: https://habr.com/ru/post/1610303/


All Articles