Reputation: 13
I have created an Array with two Strings:
var palabras: [String] = ["Gato", "Martillo"]
And I want to show the first character of this two String of the Array.
I have tried with:
letraLabel.text = palabras[round - 1].startIndex.advancedBy(0)
But i get an error: Command failed due to signal: Segmentation fault: 11 I don't know what it is mean.
And i have tried too:
letraLabel.text = palabras[round - 1].startIndex
I get an error: Cannot assign value of type 'Index' (aka 'String.CharacterView.Index') to type 'String?'
And finally I have tried:
letraLabel.text = palabras[round - 1][palabras.startIndex]
But also I got an error: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion
How can I get the first character of the two word of the Array? So, is necessary import Foundation for obtain the first character of a String? By the way, when i write "import Foundation" the compiller show me Foundation with a crossed-out line.
Upvotes: 0
Views: 4130
Reputation: 154583
Try:
letraLabel.text = String(palabras[round - 1].first!)
If you want to create another array with just the first letters:
let palabras = ["Gato", "Martillo"]
let firstLetters = palabras.map { String($0.first!) }
print(firstLetters) // ["G", "M"]
Upvotes: 4
Reputation: 76
You can also perform this easier it's nested but get's the job done. Say you had a variable with two string. You could simply use
someLabel.text = firstName.characters.first?.description + lastName.characters.first?.description
Upvotes: 0
Reputation: 5787
You were close I think. Give this a try
let charStr = palabras[round - 1]
letraLabel.text = charStr.substringToIndex(charStr.startIndex.advancedBy(1))
or if you want all the first characters concatenated together:
letraLabel.text = palabras.map({ $0.substringToIndex($0.startIndex.advancedBy(1)) }).joinWithSeparator("")
Upvotes: 0
Reputation: 13316
How about:
for palabra in palabras {
let letra = palabra[palabra.startIndex]
// do something with letra here...
}
Or, if you don't want to iterate through every palabra
, something like this might work:
let palabra = palabras[0]
let letra = palabra[palabra.startIndex]
// do something with letra here...
Upvotes: 0