json - When convert syntax to swift 3, Type 'Any' has no subscript members? -


the error "type 'any' has no subscript members." in line return @ $0["deadline"].

this happened when converted syntax swift 3.

todolist file

fileprivate let items_key = "todoitems"  func allitems() -> [todoitem] {     let tododictionary = userdefaults.standard.dictionary(forkey: items_key) ?? [:]     let items = array(tododictionary.values)     return items.map({todoitem(deadline: $0["deadline"] date, title: $0["title"] as! string, uuid: $0["uuid"] as! string!)}).sort({(left: todoitem, right:todoitem) -> bool in         (left.deadline.compare(right.deadline) == .orderedascending)     }) } 

todoitem file

struct todoitem { var title: string var deadline: date var uuid: string  init(deadline: date, title: string, uuid: string) {     self.deadline = deadline     self.title = title     self.uuid = uuid }  var isoverdue: bool {     return (date().compare(self.deadline) == comparisonresult.ordereddescending)   } } 

first of all, cannot access value of struct using subscript syntax, have use dot syntax, this: let deadline = todoitem.deadline, todoitem instance of todoitem class.

secondly, have cast retrieved dictionary userdefaults [string:todoitem], since userdefaults.dictionary(forkey:) returns dictionary of type [string:any].

see working code below:

func allitems() -> [todoitem] {     let tododictionary = userdefaults.standard.dictionary(forkey: items_key) as? [string:todoitem] ?? [:]     let items = array(tododictionary.values)     return items.map({todoitem(deadline: $0.deadline, title: $0.title, uuid: $0.uuid)}).sort({(left: todoitem, right:todoitem) -> bool in         (left.deadline.compare(right.deadline) == .orderedascending)     }) } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -