AnyObject 数组的 indexOf 不适用于字符串

indexOf of AnyObject array not working with Strings

所以我在 playgroung 中有以下代码

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

let index = array.indexOf("")

并且 XCode 标记编译器错误

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

所以我的问题是如何获取 AnyObjects 数组中元素的索引?

试试这个

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

或者您可以使用NSArray方法:

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

切勿将 AnyObject 用作任何类型的占位符,而应使用 Any。原因:AnyObject 仅适用于 classes,Swift 使用了很多结构(Array、Int、String 等)。您的代码实际上使用 NSStrings 而不是 Swifts 本机 String 类型,因为 AnyObject 想要 class (NSString 是 class).

如果您确定它可以安全地转换,您也可以转换为 [String]

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

在更一般的情况下,当数组中的对象符合 Equatable 协议时,collectionType.indexOf 将起作用。由于 Swift String 已经符合 Equatable,因此将 AnyObject 强制转换为 String 将消除错误。

如何在集合类型自定义 class 上使用 indexOf? Swift2.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)
}

现在你可以这样使用了

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