Swift Interviewing Syntax Tips

Passionate about: Defensive Programming • Effective Engineering Documentation • Emotion-Centered Design and Microcopy
I’ve spent some time recently preparing for and completing a few rounds of interviews in Swift. Along the way, I learned a couple syntax tricks that can help simplify code and save time.
Tip #1: Convert strings to character arrays for easier indexing.
In Swift, the syntax for accessing a string character by index is somewhat verbose:
let index = someString.index(someString.startIndex, offsetBy: i) // i is the index of the character you want to access
let char = someString[index]
One way to get around this is to simply convert the string to an array of characters:
let charArray = Array(someString)
let char = charArray[i]
Tip #2: Use the default param syntax when modifying (appending to) dictionary values.
It’s common and useful to store data in the form of a dictionary where the value type is an array. However, as a safety feature of Swift, when appending an element to any value array, you’ll first need to unwrap/check if that key-value pair exists:
var snacksHash = ["fruits": ["apples", "oranges"], "candies": ["twix"]]
if var fruits = snacksHash["fruits"] {
fruits.append("bananas")
snacksHash["fruits"] = fruit
} else {
snacksHash["fruits"] = ["bananas"]
}
The above approach is a bit verbose. The syntax below achieves the same thing by declaring an empty array as the value if the subscripted element does not exist, and then appending the desired element to that empty array.
var snacksHash = ["fruits": ["apples", "oranges"], "candies": ["twix"]]
snacksHash["fruits", default: []].append("bananas")
Tip #3: Use the repeating-count initializer when instantiating a matrix/2D array.
There is no shortage of matrix Leetcode problems. Depending on the problem, it often makes sense to instantiate a matrix with pre-populated values that get modified later in the solution. To do this, you can use the repeating-count initializer like so:
var visitedMatrix = Array(repeating: Array(repeating: false, count: cols), count: rows) // cols is the number of columns, and rows is the number of rows


