To solve this challenge, you must submit a Swift file with a function that sorts the rows of data and decodes the clue.
The data is given in the form of a 2D array.
Looking at the sample data, each row of the table corresponds to a single array.
Your goal is to sort the arrays, not the data within those arrays.
Don't have Swift on your computer? Debug your code on
REPL.it
Requirements
-
Submit a Swift file with a function named “sortAndDecode”
-
func sortAndDecode(_ arr: [[Any?]]) -> (String, [[Any?]])
-
Function Parameter:
- arr: A 2D array of optional values of Any type
-
Return: A tuple with the following 2 items in the following order
-
String: The Clue, decoded from decimal (integer) ASCII values
-
[[Any?]]: The sorted array of arrays
Sorting in Swift
The easiest way to sort in Swift is with the built in sorting functions, either
sort(by: )
or sorted(by: ).
These functions take a function or closure as the argument.
The function you pass in will allow the sorter to decide if one element should go before the other.
If it returns true, the first argument should come before the second.
Consider the basic example of passing in the less than operator, which operates the same way.
let arr = [3,2,1]
arr.sort(by: <)
// arr is now [1,2,3]
But we aren't sorting integers, we're sorting arrays of optional "Any" type objects.
You'll need something more complex than <.
Read on for more tips.
Swift Optionals
In Swift, optional values can either have a value or be "nil".
To use the value in an optional, you should use optional binding.
However, our data is in arrays of optional "Any" types, and "Any" objects cannot be compared.
Strings and integers are comparable, so we need to convert the object back to its original type.
In your sort function when you compare two rows, you'll have to access the string or integer for comparison.
Optional binding and attempting to convert to a type looks like this.
if let stringVal = optionalAnyVal as? String { // Code }
Because Swift is statically typed, you need to know the type at compile time.
For this challenge, as you can see in the sample data, all arrays have 5 string elements and 1 integer element in that order.
One possible solution: Anytime you want to compare elements from indices 0-4, you should try to optionally bind to a string.
If you have to compare by the element at index 5, optionally bind to an integer.
One final hint. Consider your comparison function passed in to the sort(by: ) function.
It takes in two [Any?] arrays. It should compare them "column by column". For one comparison you have 4 cases.
item1 |
item2 |
Result |
nil |
nil |
Compare the next column |
nil |
Not nil |
return true |
Not nil |
nil |
return false |
Not nil |
Not nil |
return valueOfItem1 < valueOfItem2 |
Good Luck!