所以我在一个playground中有以下代码:
var array: [AnyObject] = ["", "2", "3"]
let index = array.indexOf("")
XCode提示编译错误:
无法将类型为'String'的值转换为预期参数类型'@noescape (AnyObject) throws -> Bool'
我的问题是,如何在包含任意对象的数组中获取元素的indexOf?
jvar array: [AnyObject] = ["", "2", "3"]
let index = (array as! [String]).indexOf("")
试试这个
var array = ["", "2", "3"]
let index = array.indexOf("")
或者您可以使用NSArray
方法:
var array: [AnyObject] = ["", "2", "3"]
let index = (array as NSArray).indexOfObject("")
永远不要使用AnyObject
作为任何类型的占位符,而应该使用Any
。原因是:AnyObject
只能用于类,而Swift使用了很多结构体(如Array、Int、String等)。实际上,您的代码使用了NSString
而不是Swift的本地String
类型,因为AnyObject
需要一个类(NSString
是一个类)。
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
[String]
,很少使用AnyObject
,特别是在Swift中! 你应该始终指定你的数组中包含的内容! - AaoIiAnyObject
是一个占位符,表示“未指定”。该数组显然是一个字符串数组,因此只需删除注释[AnyObject]
。编译器会推断出正确的类型。 - vadian