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
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
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"]
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
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>.