How to recover the first letter of a Swift array

Asked

Viewed 210 times

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 answers

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: https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language

2

  • 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

  • @Brunobafilli I think this would already yield a separate question!

  • truth you’re right! Thank you very much friend

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"]
  • 1

    Thank you guys =D worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.