I need to get the first 4 characters of a string in Swift.
Is there a function for it?
I need to get the first 4 characters of a string in Swift.
Is there a function for it?
The simplest form is the following:
var str = "Obtener n caracteres de un string con swift"
let index: String.Index = str.index(str.startIndex, offsetBy: 4)
var result: String = str.substring(to: index)
here is a string extension that can also come in handy
extension String {
func subString(startIndex: Int, length: Int) -> String {
//primero compruebo que tengo mas elementos del que me quiero posicionar
if startIndex > self.characters.count{
return self
}
let start = self.startIndex.advancedBy(startIndex)
//he de comprobar que no quiera un rango mayor al que existe
var end : Index = start
if (startIndex + length) <= self.characters.count {
end = self.startIndex.advancedBy(startIndex + length)
} else {
//me piden hasta la posicion x y no hay tantos caracteres. Devuelvo hasta el final de la cadena
end = self.startIndex.advancedBy(self.characters.count)
}
let r = start ..< end
return self.substringWithRange(r)
}
}