This error means that the expression has optional value (the value can be nil) that is not yet unwrapped, strName.first
returns an optional value of Character?
, but your function demands a returning type of String
which is not an optional type.
So, in order to fix this, you need to unwrap the optional value strName.first
, it seems like you are not familiar with optionals, here's the code for your case (choose one from two options):
func getFirstCharInName(strName: String) -> String {
// option 1: force unwrap - can cause fatal error
return String(strName.first!)
// option 2: optional binding
if let firstCharInName = strName.first {
return String(firstCharInName)
} else {
// if the optional value is nil, return an empty string
return ""
}
}
PS. I don't really understand the function trim()
in your question, but if you mean to strip away the blank spaces like " "
, you can do:
firstCharInName.trimmingCharacters(in: .whitespaces)