Obtain n characters from a string with swift


I need to get the first 4 characters of a string in Swift.

Is there a function for it?

asked by Mariano 03.10.2016 в 09:17

2 answers


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)
answered by 03.10.2016 / 10:51

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)
answered by 20.09.2017 в 12:11