BenNov
BenNov

Reputation: 1111

Converting from Sorted method to Sort in Swift 2 (Xcode 7)

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)
        })
    }

Upvotes: 1

Views: 121

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

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.

Upvotes: 1

Related Questions