0

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.

Pozo
  • 13
  • 1
  • 4
  • About your last question: http://stackoverflow.com/questions/36180575/xcode-7-3-import-module-displayed-with-strikethrough – Eric Aya Apr 30 '16 at 11:42

4 Answers4

4

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"]
vacawama
  • 150,663
  • 30
  • 266
  • 294
0

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...
Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43
0

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("")
Casey Fleser
  • 5,707
  • 1
  • 32
  • 43
0

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
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
CoderJimmy
  • 76
  • 2