It would be nice to be able to pad Array
s till a certain minimum length:
let arr = [10,20,30]
let res = arr.padding(repeating: 0, inLength: 7)
print(res) // -> [10,20,30,0,0,0,0]
Incase the original array is already greater or equal to the minimum length specified, in this case 7
, then it won't do anything:
let arr = ["A","B","C","D","E","F","G","H"]
let res = arr.padding(repeating: "-", inLength: 7)
print(res) // -> ["A","B","C","D","E","F","G","H"]
This will be useful when the array is of an arbitrary length but we need atleast some minimum length to work with, so padding the array with default values is a conventional way to handle such a scenario.
The basic implementation of this can be as simple as:
extension Array {
func padding(repeating element: Element, inLength length: Int) -> [Element] {
guard self.count < length else { return self }
let paddingCount = length - self.count
let result = self + Array(repeating: element, count: paddingCount)
return result
}
}