Avoid Nesting Functions in Swift

Not harmless at all!

Steven Curtis
4 min readJan 21, 2023
Photo by Fabrizio Frigeni on Unsplash

Prerequisites:

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…

--

--

No responses yet