[英]Swift3 error: Cannot assign value of type '()' to type '[customObject]?'
I have a custom class containing 2 properties as below 我有一个包含2个属性的自定义类,如下所示
class CustomObjectClass: NSObject {
override init() {
//AppointmentsDetails
}
var customName:String?
var customDate:Date?
}
I am try to create group object of custom class by date using dictionary like Date:[CustomObjectClass] 我尝试使用类似Date的字典按日期创建自定义类的组对象:[CustomObjectClass]
While trying to iterate through object and add to the dictionary I get error : Cannot assign value of type ()
to type [CustomObjectClass]?
尝试遍历对象并将其添加到字典时,出现错误:无法将类型
()
值分配给[CustomObjectClass]?
类型[CustomObjectClass]?
code is below 代码在下面
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
var tempCustObj = CustomObjectClass()
var tempCustList = [CustomObjectClass]()
for obj in customlist{
dateDict[obj.customDate!] = tempCustList.append(obj)
//error : Cannot assign value of type '()' to type '[CustomObjectClass]?'
}
}
var custObj = CustomObjectClass()
var customlist = [CustomObjectClass]()
var dateDict = [Date:[CustomObjectClass]]()
}
can some one suggest a solution for this 有人可以为此提出解决方案吗
tempCustList.append(obj)
returns Void ("nothing") so you can't add it to the dictionary tempCustList.append(obj)
返回Void(“无”),因此您无法将其添加到字典中
If you want to add obj
, first you'd need to check if there's an array or not (create a new one otherwise), append the element to the array and finally set the value of the dictionary. 如果要添加
obj
,首先需要检查是否存在一个数组(否则请创建一个新数组),然后将该元素附加到数组中,最后设置字典的值。
for obj in customlist {
if classesByDate[obj.customDate!] == nil {
classesByDate[obj.customDate!] = [obj]
} else {
classesByDate[obj.customDate!]!.append(obj)
}
}
Thanks to the new Dictionary API, you can simply use an initializer: 有了新的Dictionary API,您可以简单地使用初始化程序:
let classesByDate = Dictionary(grouping: customlist) { $0.customDate! }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.