Search code examples
swiftxcodesf-symbols

How do I use an SF Symbol in Swift using its symbol literal instead of its name?


The normal way to use an SF Symbol is to find the image you want in the SF Symbols app, copy its name, and then use this name in the Image(systemName:) constructor. For example, if I'd like to display the share Icon, I could use the following code:

Image(systemName: "square.and.arrow.up")

This will produce the following image in the UI:

enter image description here

This is great, but just like color and image literals, I was hoping that instead of the string square.and.arrow.up I could have something more literal in my code. For example, if I choose "Copy symbol" in SF Symbols and then paste that into Xcode, I get a string which represents a "symbol literal":

enter image description here

If I try using that code, though, I get the following error:

enter image description here

No symbol named '􀈂' found in system symbol set

Is there another way to use this Symbol within Xcode and have it provide me an Image with the corresponding systemName so I can stop using the string square.and.arrow.up in my codebase and instead use the symbol literal?


My current workaround is to add the literal symbol as a comment, but I'd like to avoid duplicating the symbol:

enter image description here

Other things I've tried:

  • Image(_ name:bundle:): This doesn't show anything.
  • Text(_ content:): This shows a black square with a question mark.
  • Using an #imageLiteral: I investigated this a while ago but couldn't find a way to do this.

Solution

  • Image literals don't work in Xcode these days, and haven't worked for a long time. You have to refer to the string "square.and.arrow.up" in order to specify this image; there is no other way. You can give the string a synonym; you can use the storyboard to fetch the image into an image view so that you don't have to do it in code; but there is no other "magic" way such as you are envisioning.