我有一个包含2个属性的自定义类,如下所示
class CustomObjectClass: NSObject {
override init() {
//AppointmentsDetails
}
var customName:String?
var customDate:Date?
}
我尝试使用Date这样的字典创建自定义类的组对象:[CustomObjectClass]
在尝试迭代对象并添加到字典时,我收到错误:无法将类型()
的值指定为[CustomObjectClass]?
代码在
之下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]]()
}
有人可以为此建议解决方案
答案 0 :(得分:1)
tempCustList.append(obj)
返回Void(“无”),因此您无法将其添加到词典
如果要添加obj
,首先需要检查是否有数组(否则创建一个数组),将元素追加到数组中,最后设置字典的值。
for obj in customlist {
if classesByDate[obj.customDate!] == nil {
classesByDate[obj.customDate!] = [obj]
} else {
classesByDate[obj.customDate!]!.append(obj)
}
}
感谢新的Dictionary API,您只需使用初始化程序:
let classesByDate = Dictionary(grouping: customlist) { $0.customDate! }