-1

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

1 Answers1

5

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 ?? ""))
Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30
  • Thank you so much, this was so trivial so I'm sorry to take up your time: It worked! I am quite new to swift as I have had to learn it for my senior year project in school and some of these basic things slip me sometimes. You've helped immeasurably as I can now continue with my Major Work. Thanks :) – Garfunklefinn Jul 12 '21 at 00:51