<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class="">Hi everyone!<br class=""><div class=""><br class=""></div><div class="">I’ve been<a href="https://github.com/adrfer/Sort" class=""> tinkering with a few sorting algorithms in Swift</a> and noticed a diference in behaviour when it comes to accessing the first element of a collection.</div><div class=""><br class=""></div><div class="">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. </div><div class=""><br class=""></div><div class="">For example, when using subscripting:</div><div class=""><br class="">func quickSort(array: [Int]) -> [Int] {<br class=""><br class=""> guard array.count > 1 else { return array }<br class=""><br class=""> let (pivot, rest) = (<b class="">array[0]</b>, array.dropFirst())<b class=""> // no need to unwrap `pivot` for further use</b><br class=""><br class=""> let lessThan = rest.filter({ $0 < <b class="">pivot</b> })<br class=""><br class=""> let greaterThanOrEqual = rest.filter({ $0 >= <b class="">pivot</b> })<br class=""><br class=""> return quickSort(lessThan) + [<b class="">pivot</b>] + quickSort(greaterThanOrEqual)<br class="">}</div><div class=""><br class=""></div><div class="">But, when using the method `first`:</div><div class=""><br class=""></div><div class="">func quickSort(array: [Int]) -> [Int] {<br class=""><br class=""> guard array.count > 1 else { return array }<br class=""><br class=""> let (pivot, rest) = (<b class="">array.first</b>, array.dropFirst())<br class=""><br class=""> let lessThan = rest.filter({ $0 < <b class="">pivot</b> })<b class=""> // unwrapping `pivot` is not required here</b><br class=""><br class=""> let greaterThanOrEqual = rest.filter({ $0 >= <b class="">pivot</b> })<b class=""> // unwrapping `pivot` is not required here</b><br class=""><br class=""> return quickSort(lessThan) + [<b class="">pivot!</b>] + quickSort(greaterThanOrEqual)<b class=""> // unwrapping `pivot` is now required here</b><br class="">}</div><div class=""><br class=""></div><div class="">Isn’t the subscript supposed to return an optional as well?</div><div class=""><br class=""></div><div class="">Why unwrapping isn't required when `pivot` is used within the `filter` call?</div><div class=""><br class=""></div><div class="">Best,</div><div class=""><br class=""></div><div class="">— A</div></body></html>