user842225
user842225

Reputation: 5979

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

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?

Upvotes: 7

Views: 9615

Answers (3)

Avijit Nagare
Avijit Nagare

Reputation: 8782

My method written in object c which return NSMutableArray of type "Database"

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

In swift i declare 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 help someone.

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70097

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.

Upvotes: 8

iAnurag
iAnurag

Reputation: 9356

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

Upvotes: 3

Related Questions