Efficient DSA Coding Boilerplate Using Swift’s Built-in Methods

Rahul Goel
2 min readApr 29, 2024

--

Fast track your DSA round by using commonly used in-built methods of Swift Programming language.

1. String

let str = "Hello"
let count = str.count // count is 5

let str = ""
let isEmpty = str.isEmpty // isEmpty is true

let str = "Hello, World!"
let contains = str.contains("World") // contains is true

let str = "Hello, World!"
let hasPrefix = str.hasPrefix("Hello") // hasPrefix is true

let str = "Hello, World!"
let hasSuffix = str.hasSuffix("World!") // hasSuffix is true
//Convert String to character array - @therahulgoel

let str = "Hello"
let charArray = Array(str)
print(charArray) // Output: ["H", "e", "l", "l", "o"]

let str = "Hello, World!"

// Get the prefix of length 3
let prefix = str.prefix(3)
print(prefix) // Output: "Hel"

// Get the suffix of length 3
let suffix = str.suffix(3)
print(suffix) // Output: "ld!"

let str = "Hello, World!"
let substrings = str.split(separator: ",") // substrings is ["Hello", " World!"]

2. Arrays

// Find min and max of given array

let numbers = [5, 3, 9, 1, 7]

// Find the minimum value
if let minValue = numbers.min() {
print("Minimum value in the array: \(minValue)")
} else {
print("Array is empty")
}

// Find the maximum value
if let maxValue = numbers.max() {
print("Maximum value in the array: \(maxValue)")
} else {
print("Array is empty")
}

let array = ["Hello", "World"]
let joinedString = array.joined(separator: ", ") // joinedString is "Hello, World"


let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0, +) // sum is 15 (1 + 2 + 3 + 4 + 5)

let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
let rowCount = matrix.count // Number of rows
let columnCount = matrix[0].count // Number of columns (assuming all rows have the same number of elements)

3. Maths

let x = -5
let absoluteValue = abs(x) // absoluteValue is 5

let a = 5
let b = 3
let minimum = min(a, b) // minimum is 3
let maximum = max(a, b) // maximum is 5

let x = 2
let y = 3
let result = pow(x, y) // result is 8

let x = 9
let squareRoot = sqrt(Double(x)) // squareRoot is 3.0

let x = 3.7
let ceiling = ceil(x) // ceiling is 4.0
let floorValue = floor(x) // floorValue is 3.0

let x = 3.4
let roundedValue = round(x) // roundedValue is 3.0

let randomNumber = Int.random(in: 1...100) // Generate a random number between 1 and 100

Follow me Rahul Goel for further updates.

--

--

Rahul Goel

Computer Science Enthusiast | 11+ Year of Software Evolution | @Sharechat, Groupon, Paytm, Myntra https://www.linkedin.com/in/therahulgoel/