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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With