Hi everyone!
I’ve been tinkering with a few sorting algorithms in Swift <https://github.com/adrfer/Sort> and noticed a diference in behaviour when it comes to accessing the first element of a collection.
If the method `first` from `CollectionType` is used, one needs to unwrap the returned optional to use it. Pretty standard stuff... However, if one uses subscripting, no unwrapping is required.
For example, when using subscripting:
func quickSort(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let (pivot, rest) = (array[0], array.dropFirst()) // no need to unwrap `pivot` for further use
let lessThan = rest.filter({ $0 < pivot })
let greaterThanOrEqual = rest.filter({ $0 >= pivot })
return quickSort(lessThan) + [pivot] + quickSort(greaterThanOrEqual)
}
But, when using the method `first`:
func quickSort(array: [Int]) -> [Int] {
guard array.count > 1 else { return array }
let (pivot, rest) = (array.first, array.dropFirst())
let lessThan = rest.filter({ $0 < pivot }) // unwrapping `pivot` is not required here
let greaterThanOrEqual = rest.filter({ $0 >= pivot }) // unwrapping `pivot` is not required here
return quickSort(lessThan) + [pivot!] + quickSort(greaterThanOrEqual) // unwrapping `pivot` is now required here
}
Isn’t the subscript supposed to return an optional as well?
Why unwrapping isn't required when `pivot` is used within the `filter` call?
Best,
— A