swifterror-handlingswiftuiswift-optionals

Why is 'Fatal error: Unexpectedly found nil while unwrapping an Optional value' showing despite no nil values being present?


I've been investigating this error for a while and I am still struggling to find an answer.

I understand the concept behind this error yet I don't understand why it is still notifying me even though I feel as if I have removed any nil values from the equation (<- phrase, not code).

struct NickName: View {

var name: String = ""
@AppStorage("current_user") var user = ""

var body: some View {
    
    Text(String(name.first!)) //It notifies me here, i.e. 'Thread 1: Fatal error...'
        .fontWeight(.heavy)
        .foregroundColor(.white)
        .frame(width: 50, height: 50)
        .background((name == user ? Color.blue : Color.green).opacity(0.5))
        .clipShape(Circle())
}}

This structure is passed through a series of views where it should be presented in a messaging interface.

Thanks for any help, I feel as though I've just been looking at this the wrong way or maybe I am missing something and it is an easy fix :)


Solution

  • var name: String = "" is an empty String.

    name.first should return you first Character in the String optionally if it is present.

    For your example, since this is an empty String, it will be nil.

    When you force cast something that is nil, it will crash your app with the message that you are seeing.

    Solution :

    Text(String(name.first ?? ""))