Swift3错误:无法指定类型'()'的值来键入'[customObject]?'

时间:2017-07-24 20:40:39

标签: ios swift swift3

我有一个包含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]]()
}

有人可以为此建议解决方案

1 个答案:

答案 0 :(得分:1)

Swift 3

tempCustList.append(obj)返回Void(“无”),因此您无法将其添加到词典

如果要添加obj,首先需要检查是否有数组(否则创建一个数组),将元素追加到数组中,最后设置字典的值。

for obj in customlist {
    if classesByDate[obj.customDate!] == nil {
        classesByDate[obj.customDate!] = [obj]
    } else {
        classesByDate[obj.customDate!]!.append(obj)
    }
}

Swift 4

感谢新的Dictionary API,您只需使用初始化程序:

let classesByDate = Dictionary(grouping: customlist) { $0.customDate! }