swiftimageswiftuisf-symbols

Check if SF Symbol exists Swift


I want to display a SwiftUI Image with a number. I might do so like this:

let number = 13
Image(systemName: "\(number).square.fill")

However, not every number has an SF Symbol — what if I wanted to display 134.square.fill but discovered that there isn't one, crashing the app?

How can I check if an SF Symbol exists without crashing the app?


Solution

  • The following code will show the question mark symbol, if one for the number does not exist. But you can adapt it to do anything.

    struct ContentView: View {
        var body: some View {
            let number = 144
    
            return VStack {
                Image(uiImage: UIImage(systemName: "\(number).square.fill") ?? UIImage(systemName: "questionmark.square.fill")!)
            }
        }
    }