Making text bold using attributed string in swift
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
If you need only part of a string to appear bold in Swift, an attributed string is the right tool. The exact API depends on whether you are working in UIKit or AppKit with NSAttributedString, or in newer Swift and SwiftUI code with the native AttributedString type.
Bold text with NSMutableAttributedString
In UIKit and AppKit code, the most direct approach is to create a mutable attributed string and apply a bold font to the range you want.
You can assign attributed directly to a UILabel, UITextView, or other UIKit view that supports attributed text:
This pattern is simple and works well when the bold portion is known as a substring.
Preserve the existing font family when bolding
UIFont.boldSystemFont is convenient, but it changes the font family. If the label already uses a custom font, you usually want the bold version of that same family instead.
This produces bold text without unexpectedly switching to the system font. That detail matters more than many examples admit, especially in apps with a defined visual style.
Use Swift's native AttributedString in newer code
If you are working in SwiftUI or modern Foundation APIs, AttributedString can be cleaner:
In SwiftUI, you can render it directly:
This is often nicer than bridging through NSAttributedString unless you specifically need UIKit or AppKit APIs.
Apply bold styling to multiple ranges
If the same text contains several emphasized fragments, apply attributes range by range:
This is a good approach for label-value strings, chat highlights, invoice totals, and other structured text where a few fixed fragments need emphasis.
Common Pitfalls
The most common mistake is using String.Index ranges directly with NSAttributedString APIs. Most UIKit and AppKit attribute methods still expect NSRange, so bridge through NSString or convert carefully.
Another common issue is bolding a substring that does not exist. Always guard against NSNotFound, especially when the content comes from user data or localization.
People also accidentally replace a custom font with boldSystemFont. If maintaining the exact font family matters, derive the bold font from the original descriptor instead.
Finally, remember that AttributedString and NSAttributedString are related but not identical. Choose the one that fits the UI framework you are actually using instead of mixing them by habit.
Summary
- Use
NSMutableAttributedStringwith a.fontattribute for UIKit or AppKit code. - Convert substring matches to
NSRangebefore applying attributes. - Preserve custom font families by deriving a bold descriptor from the existing font.
- Prefer native
AttributedStringin modern SwiftUI-friendly code. - Guard missing ranges and localization changes so your bolding logic stays safe.

