Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign a value of type 'NSArray' to a value of type '[AnyObject]'

Tags:

ios

swift

In swift, I have an School class, it has an students property of type [AnyObject]!

class School : NSObject {
  var students: [AnyObject]!
  ...
}

I got an instance of School, and an NSArray of string representing students' names. I want to assign this NSArray variable to students:

var school = School()
var studentArray : NSArray = getAllStudents()

//ERROR:Cannot assign a value of type 'NSArray' to a value of type '[AnyObject]'
school.students = studentArray

Why this error? Isn't array in swift compatible with NSArray in objective c??? How to get rid of above compiler error?

like image 746
user842225 Avatar asked Sep 07 '15 14:09

user842225


2 Answers

Your var students is a Swift array and expects object of type AnyObject, but you try assign it an NSArray. The two objects are not of the same type and it doesn't work.

But, given that NSArray is compatible with [AnyObject], you can use simple typecasting to make the NSArray into a Swift array:

school.students = studentArray as [AnyObject]

Of course a better approach would be to stay in the Swift world and to forget NSArray altogether if possible, by making getAllStudents return a Swift array instead of an NSArray. Not only you will avoid having to do typecasts but you will also benefit from the power of the Swift collections.

like image 195
Eric Aya Avatar answered Oct 14 '22 19:10

Eric Aya


Sounds like school.students is defined as Optional and might be nil therefore if you are sure that its not nil - unwrap it first by using !:

school.students as AnyObject! as NSArray

OR

school.students! as NSArray
like image 3
iAnurag Avatar answered Oct 14 '22 21:10

iAnurag