Cannot set value of type "NSArray" to value of type "[AnyObject]"

In swift, I have a School class, it has a students property like [AnyObject]!

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

I got an instance of School and an NSArray string representing the names of the students. I want to assign this variable to NSArray 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 is this a mistake? Not an array in quick compatibility with NSArray in objective c ??? How to get rid of the compiler error above?

+6
source share
3 answers

Your var students is a Swift array and expects an object of type AnyObject , but you try assigning it an NSArray . Two objects are not of the same type, and they do not work.

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

 school.students = studentArray as [AnyObject] 

Of course, the best approach would be to stay in the Swift world and forget about NSArray altogether, making getAllStudents return a Swift array instead of an NSArray. Not only will you not have to do type tricks, but you can also take advantage of Swift collections.

+6
source

It looks like school.students is defined as Optional and can be nil, so if you are sure that it is not zero, unpack it first using !:

 school.students as AnyObject! as NSArray 

OR

 school.students! as NSArray 
+2
source

My method is written in a c object that returns an NSMutableArray of type "Database"

  -(NSMutableArray *)AllRowFromTableName:(NSString *)tableName; 

In swift, I declare a variable as

 var petListArray: NSMutableArray = [] 

Save in model array as

  self.petListArray = self.dataBase.AllRowFromTableName("InsuranceTable") 

Used in cellForRowAtIndexPath

  let tempDBObject = self.petListArray[indexPath.row] as! Database cell?.petName.text = tempDBObject.Hname 

hope this helps someone.

0
source

All Articles