This function retrieves the array of item representation from disk, converts it to an array of TodoItem instances using an unnamed closure we pass to map, and sorts that array chronologically. Sorted doesn't work anymore, I get an error to switch to sort. But I can't seem to get it right. Whatever I do results in various errors.
func allItems() -> [TodoItem] {
var todoDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(ITEMS_KEY) ?? [:]
let items = Array(todoDictionary.values)
return items.map({TodoItem(deadline: 0ドル["deadline"] as! NSDate, title: 0ドル["title"] as! String, UUID: 0ドル["UUID"] as! String!)}).sorted({(left: TodoItem, right:TodoItem) -> Bool in
(left.deadline.compare(right.deadline) == .OrderedAscending)
})
}
asked Oct 28, 2015 at 20:21
1 Answer 1
Just replace sorted
by sort
, it looks like you've already done the rest of the translation (I can't check, not knowing how it was before):
func allItems() -> [TodoItem] {
var todoDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(ITEMS_KEY) ?? [:]
let items = Array(todoDictionary.values)
return items.map( {TodoItem(deadline: 0ドル["deadline"] as! NSDate, title: 0ドル["title"] as! String, UUID: 0ドル["UUID"] as! String!)} ).sort( {(left: TodoItem, right:TodoItem) -> Bool in
(left.deadline.compare(right.deadline) == .OrderedAscending)
})
}
Reminder: sorted
has become sort
and the old sort
is now sortInPlace
.
answered Oct 28, 2015 at 20:38
-
Be careful, this has changed again in Swift 3, where
sort
is the mutating method, andsorted
is the one returning a new array.Eric Aya– Eric Aya2016年06月01日 18:12:43 +00:00Commented Jun 1, 2016 at 18:12
lang-swift