Skip to content

Instantly share code, notes, and snippets.

@fitomad
Created April 19, 2018 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitomad/91eb6b29f494dfe93f42cf170e28efad to your computer and use it in GitHub Desktop.
Save fitomad/91eb6b29f494dfe93f42cf170e28efad to your computer and use it in GitHub Desktop.
import Foundation
// Vamos a añadir caracteres a la derecha.
// Pasamos de unidades a decenas
for numero in 1...9
{
let cadena: String = "\(numero)"
// La función `padding` la encontramos en NSString
let resultado: String = cadena.padding(toLength: 2, withPad: "0", startingAt: 0)
print(resultado)
}
/*
10
20
30
40
50
60
70
80
90
*/
//
// ¿Y si queremos añadir caracteres al inicio?
//
extension String
{
/**
Añade a la izquierda del String un caracter tantas
veces como se indica.
En caso que la longitud de la cadena actual sea igual
o superior la longitud que se especifica como parámetro
obviamos la operación.
- Parameters
- length: Longitud total de la cadena resultante
- pad: El caracter que queremos añadir
- Result: Una nueva cadena con el formato requerido
*/
func paddingLeft(toLength lenght: Int, withPad pad: Character) -> String
{
if self.count < lenght
{
let the_pad: String = String(repeating: pad, count: (lenght - self.count))
return "\(the_pad)\(self)"
}
return self
}
}
for numero in 1...10
{
let cadena: String = "\(numero)"
let resultado: String = cadena.paddingLeft(toLength: 2, withPad: "0")
print(resultado)
}
/*
01
02
03
04
05
06
07
08
09
10
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment