[英]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]!
在swift中,我有一个
School
类,它有一个类型为[AnyObject]!
的students
属性[AnyObject]!
class School : NSObject {
var students: [AnyObject]!
...
}
I got an instance of School
, and an NSArray
of string representing students' names. 我得到了一个
School
的实例,以及一个代表学生姓名的NSArray
字符串。 I want to assign this NSArray
variable to students
: 我想将这个
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 this error? 为什么这个错误? Isn't array in swift compatible with NSArray in objective c???
是不是swift中的数组与目标c中的NSArray兼容? 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
. 你的var
students
是一个Swift数组,并期望AnyObject
类型的AnyObject
,但你尝试为它分配一个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: 但是,鉴于
NSArray
与[AnyObject]
兼容,您可以使用简单的类型转换将NSArray
转换为Swift数组:
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. 当然,更好的方法是留在Swift世界并尽可能地忘记NSArray,方法是让
getAllStudents
返回一个Swift数组而不是NSArray。 Not only you will avoid having to do typecasts but you will also benefit from the power of the Swift collections. 您不仅可以避免必须进行类型转换,还可以从Swift集合的强大功能中受益。
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
被定义为Optional,因此如果你确定它不是nil可能是nil - 首先使用!解包它:
school.students as AnyObject! as NSArray
OR 要么
school.students! as NSArray
My method written in object c which return NSMutableArray of type "Database" 我在object c中编写的方法返回类型为“Database”的NSMutableArray
-(NSMutableArray *)AllRowFromTableName:(NSString *)tableName;
In swift i declare variable as 在swift中我声明变量为
var petListArray: NSMutableArray = []
Save in model array as 将模型数组保存为
self.petListArray = self.dataBase.AllRowFromTableName("InsuranceTable")
Used in cellForRowAtIndexPath 用于cellForRowAtIndexPath
let tempDBObject = self.petListArray[indexPath.row] as! Database
cell?.petName.text = tempDBObject.Hname
hope this help someone. 希望这有帮助的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.