1
I would like to know how to retrieve the first letter of an array element
var wordEasy = ["uva", "manga"]
var teste: String = wordEasy[0]
I would like to retrieve only the letter u
1
I would like to know how to retrieve the first letter of an array element
var wordEasy = ["uva", "manga"]
var teste: String = wordEasy[0]
I would like to retrieve only the letter u
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"
2
If you do not want to use the extension suggested in Jeferson’s answer, use the same method as her:
var wordEasy = ["uva", "manga"]
var teste: String = wordEasy[0]
let u = teste[teste.startIndex]
print(u)
Worth a look at Apple’s official reference on strings on Swift.
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 of 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"]
Thank you guys =D worked!
Browser other questions tagged string swift
You are not signed in. Login or sign up in order to post.
The two answers are great, because I got one more problem, I need to assign each letter in a different variable, I think starIndex is not right, is there any other way for me to do this? i did so <i>Let word = wordEasy[0] for var i = 0; i < wordEasy.Count print(word.stringByPaddingToLength(1, withString: "", startingAtIndex: 2))</i> but I don’t think it’s cool because I don’t use withString
– Bruno Bafilli
@Brunobafilli I think this would already yield a separate question!
– bfavaretto
truth you’re right! Thank you very much friend
– Bruno Bafilli