Pasific_Dev Pasific_Dev - 3 years ago 100
Swift Question

Swift3 error: Cannot assign value of type '()' to type '[customObject]?'

I have a custom class containing 2 properties as below

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]

While trying to iterate through object and add to the dictionary I get error : Cannot assign value of type
()
to type
[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

Answer Source

Swift 3

tempCustList.append(obj) returns Void ("nothing") so you can't add it to the dictionary

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.

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

Swift 4

Thanks to the new Dictionary API, you can simply use an initializer:

let classesByDate = Dictionary(grouping: customlist) { $0.customDate! }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download