NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Text: Counting Number of Elements from LocalizedStringKey with SF Symbols

Forums > 100 Days of SwiftUI


I am trying to create a custom text view and want to be able to use SF Symbols with it. I am aware of text elements in SwiftUI being able to take a LocalizedStringKey, and how you can interpolate certain accepted things into one. In my specific case, I want to interpolate an SF Symbol in a text element:

Text("CAMERA \(Image(systemName: "camera"))")

This should display the word "CAMERA" with a camera SF Symbol next to it.

My problem is that I need to count the number of elements in this text element, but not the literal value passed in. Rather, I want to count the number of elements from how it is displayed. So, I would count the number of characters in "CAMERA" (which is six) and then count the space next to it (which is one), then the SF Symbol as another character (which is of course one). Then, the total number of characters in my original text element would be eight.

Basically, I need to be able to count the number of characters in a LocalizedStringKey and count symbols as one character. LocalizedStringKey does not have a .count member, so I need to figure out a way to do this by myself.

To be crystal clear, my goal is to have behavior similar to how Swift counts the characters in a string with emojis:

let string = "CAMERA 📸"
print(string.count) // 8

I want this to work for SF Symbols in a text element though. Any help/clarification? Thanks! :)


Unlike an emoji, which is unicode text, a SF Symbol is a vector graphic and not text. So you can't count it like an emoji.

You could use Label instead of Text, though.



You could try to replace the SF Symbol with a space or any other character and then count that,

let string = "camera \(Image(systemName: "camera"))"
print(string.replacing(/Image(.+?)\)/, with: " ").count)


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.