How to retrieve the first letter of a Swift array

1

I would like to know how to retrieve the first letter of an element from an array

var wordEasy = ["uva", "manga"]

var teste: String = wordEasy[0]

I would like to retrieve only the letter u

    
asked by anonymous 22.01.2016 / 18:07

3 answers

0

You can extend the Array type using where clause to extend only elements that can be converted to String. Create a property to return an array of Strings. Use map to convert each element to String, extract the first element from the character array using the prefix (n) property of the characters, and convert the Character to String before returning it.

extension Array where Element: StringLiteralConvertible {
    var initials: [String] {
        return map{String(String($0).characters.prefix(1))}
    }
}

Testing:

let frutas = ["uva", "manga"]

let frutasInitials = frutas.initials   // ["u","m"]
    
22.01.2016 / 20:52
3

You can use this extension

extension String {

  subscript (i: Int) -> Character {
    return self[self.startIndex.advancedBy(i)]
  }

  subscript (i: Int) -> String {
    return String(self[i] as Character)
  }

  subscript (r: Range<Int>) -> String {
    let start = startIndex.advancedBy(r.startIndex)
    let end = start.advancedBy(r.endIndex - r.startIndex)
    return self[Range(start: start, end: end)]
  }
}

The result:

"abcde"[0] === "a"
"abcde"[0...2] === "abc"
"abcde"[2..<4] === "cd"

Credits: link

    
22.01.2016 / 18:10
2

If you do not want to use the suggested extension in the Jeferson answer , use the same method as it:

var wordEasy = ["uva", "manga"]
var teste: String = wordEasy[0]
let u = teste[teste.startIndex]
print(u)

Another look at the official Apple reference on Swift strings a>.

    
22.01.2016 / 18:13