How to use string to load SF Symbol Image and if SF Symbol with that name isn't available, load user uploaded image with that string name instead

Viewed 533

In my SwiftUI app, I have string names that are the name of an SF Symbol Image, or Images stored in the asset catalog.

I would like to create a view that first tries to display the image as an SF symbol image and if an SF Symbol Image with that name doesn't exist to display an Image from my asset catalog instead.

struct ImagePresenter: View {

    let name: String = "test"
    
    var body: some View {
        Group {
            if Image(systemName: name) == nil {
                Image(name)
            } else {
                Image(systemName: name)
            }
        }
    }
}
1 Answers

You can't use Image(systemName:) for nil comparison as it doesn't return an optional.

Try with UIImage instead:

import SwiftUI
import UIKit

struct ContentView: View {
    let name: String = "test"

    var body: some View {
        Group {
            if UIImage(systemName: name) == nil {
                Image(name)
            } else {
                Image(systemName: name)
            }
        }
    }
}
Related