Home > Software design >  Get first character of string and save in variable
Get first character of string and save in variable

Time:09-11

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

CodePudding user response:

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.

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)}
}

CodePudding user response:

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