1

i'm trying to display the first letter of my contact name in uppercase:

 var firstLetter: String? = !(contact?.firstName == "") ? (contact?.firstName as? String)?.substring(to: 1).uppercased() : (contact?.lastName as? String)?.substring(to: 1).uppercased()

but i have got this error:

String may not be indexed with 'Int', it has variable size elements
Hamish
  • 78,605
  • 19
  • 187
  • 280
khouloud
  • 107
  • 11
  • 1
    `String` is indexed by `String.Index`, not `Int`, compare [How does String.Index work in Swift 3](https://stackoverflow.com/q/39676939/2976878). Although in your case, you can use `string.characters.first`, which will give you the first character of the string, or `nil` if the string is empty – compare [How to get first letter of all strings in an array in iOS Swift?](https://stackoverflow.com/q/33792991/2976878). – Hamish May 30 '17 at 08:54
  • What type is contact here? Can you show the definition of "contact" type? – PGDev May 30 '17 at 09:44

5 Answers5

0

Try this function to get first letter in capital format. Before the call check if your string is empty then don't call as you are doing in your code

func capitalizeFirst() -> String {
        let firstIndex = self.index(startIndex, offsetBy: 1)
        return self.substring(to: firstIndex).capitalized + self.substring(from: firstIndex).lowercased()
    }
Hamish
  • 78,605
  • 19
  • 187
  • 280
Matloob Hasnain
  • 1,025
  • 6
  • 21
0

If you just need to find the first character, you can use contact?.uppercased().characters.first. In general, to get the n-th character in uppercase, use contact?.uppercased()[contact?.index(contact?.startIndex, offsetBy: n)]

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
0

Try this:

    if let contact = contact
    {
        var firstLetter = !contact.firstName.isEmpty ? contact?.firstName.characters.first?.description.uppercased() : contact?.lastName.characters.first?.description.uppercased()
    }

I will be able to help you more if you tell the type/definition of "contact".

PGDev
  • 23,751
  • 6
  • 34
  • 88
0

To avoid the long chain of indirections and make the function a bit clearer you could also write it like this :

firstLetter = ( (contact?.firstName ?? "") + (contact?.lastName ?? "") )
              .characters.first?.description.uppercased()
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0
var firstLetter = (contact?.firstName.characters.first ?? contact?.lastName.characters.first)?.description.uppercased()
bzz
  • 5,556
  • 24
  • 26