Get first character of string and save in variable

Viewed 56

I'm trying to get the first letter of a string and store it in another variable which is a string.

So far I have

func getFirstChar(deckName : String) -> String {
    return String(deckName.first)
}

From what I understand from googling this should work, but it doesn't compile with the error

No exact matches in call to initializer

2 Answers

As Joan says, String.first returns an Optional. I'm always leery about using force-unwrapping since it crashes if the thing you are unwrapping is nil, so I would advise against the suggestion of using it to return a non optional string.


Edit

Leo Dabus pointed out that you could write this function using String.prefix(_:), which (apparently) doesn't return an Optional. That lets you avoid all that mucking about with optionals. That version of the function might look like this:

func getFirstChar(_ deckName : String) -> String {
    return String(deckName.prefix(1))
}

Below are other options of dealing with the optionals returned by String.first:

I'd suggest a variation on Joan's answer instead:

func getFirstChar(_ deckName : String) -> String {
    return String(deckName.first ?? Character(""))
}

Or

func getFirstChar(_ deckName : String) -> String {
    return deckName.first.map {String($0)} ?? ""
}

Either of those versions will return an empty string if first returns nil (a reasonable return value.)

A third choice is to return an Optional string:

func getFirstChar(_ deckName : String) -> String? {
    return deckName.first.map {String($0)}
}

The problem is that first produces an optional. If you are sure that the deck name won't be nil then use this:

func getFirstChar(_ deckName : String) -> String {
        return String(deckName.first!)
    
}
Related