1

I am migrating my code from Swift 2.3 to Swift 3. Before it was working fine after migrating I am facing not expected contextual result type NSArray Here is my code

func setConfirmedBookingsAfterSorting() {
        if let bookings =  ContentService.sharedInstance.confirmedBookings {
            self.confirmedBookings = (bookings as NSArray).sortedArray(using: [NSSortDescriptor(key: "startTime", ascending: true)])
        }
    }
Jules
  • 14,841
  • 9
  • 83
  • 130
srinitha
  • 119
  • 10

1 Answers1

1

The declared type of the method used is func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any], which means the result is implicitly converted to a Swift array.

Try this:

((bookings as NSArray).sortedArray(using: [NSSortDescriptor(key: "startTime", ascending: true)])) as NSArray

This prevents the conversion and maintains the result as an NSArray Objective C object.

Jules
  • 14,841
  • 9
  • 83
  • 130
breno morais
  • 85
  • 1
  • 11
  • This looks decidedly more complicated than [Alexander's suggestion](https://stackoverflow.com/questions/41476693/swift3-not-the-expected-contextual-result-type-nsarray#comment70159404_41476693): can you describe advantages? – greybeard Jun 01 '17 at 14:03
  • @greybeard - it's a more minimal modification of the code in the question than the suggestion in the comment, which some people may prefer. Specifically, it doesn't require changing the type of any declarations, and it doesn't change the behaviour from returning a sorted copy to an in-place sort. – Jules Jul 19 '18 at 19:29
  • @brimstone - the declared type of the method used is `func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any]`, which means the result is implicitly converted to a Swift array. This prevents the conversion and maintains the result as an `NSArray` Objective C object. – Jules Jul 19 '18 at 19:33