Avoid Nesting Functions in Swift
Not harmless at all!
4 min readJan 21, 2023
Prerequisites:
- You will need to be familiar with the basics of Swift and able to start a Playground (or similar)
- You should know something about weak references
Terminology:
Function: a group of statements that together can perform some action
Background
One of the things about completing LeetCode Challenges is that completing them helps you to explore the limits of your chosen language (in this case, we are talking about Swift).
Now one of the challenges that seems to re-emerge when completing these contests is using a Binary Search (an example of this is challenge 1552) which asks the programmer to develop a Binary Search but with a custom function to decide whether we look to the left of the right of mid point.
class Solution {
func maxDistance(_ position: [Int], _ m: Int) -> Int {
let position = position.sorted()
let length = position.count
func ballsWillFit(_ d: Int) -> Int {
var result = 1
var cur = position[0]
for pos in position where (pos - cur) >= d {
cur = pos
result += 1
}
return result…