Swift syntax
subscript
superscript
Swift programming
text styling

How do I use subscript and superscript in Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Swift, subscript and superscript text are usually a text-rendering problem, not a language feature. The common solution is to style part of a string with a smaller font and a shifted baseline so the characters visually sit lower or higher than the surrounding text.

UIKit with NSAttributedString

For UILabel, UITextView, and many other UIKit views, NSAttributedString is the standard tool. The main attribute is .baselineOffset, and it usually looks best when paired with a smaller font.

swift
1import UIKit
2
3let baseFont = UIFont.systemFont(ofSize: 24)
4let subscriptFont = UIFont.systemFont(ofSize: 16)
5
6let text = NSMutableAttributedString(
7    string: "H2O",
8    attributes: [.font: baseFont]
9)
10
11text.addAttributes(
12    [
13        .font: subscriptFont,
14        .baselineOffset: -6
15    ],
16    range: NSRange(location: 1, length: 1)
17)
18
19let label = UILabel()
20label.attributedText = text

That creates a lowered 2 for a typical chemical formula. The exact offset value depends on the font family and base size, so treat it as a design value, not a universal constant.

Superscript Uses the Same Pattern

Superscript is the same idea with a positive baseline offset.

swift
1import UIKit
2
3let baseFont = UIFont.systemFont(ofSize: 24)
4let superscriptFont = UIFont.systemFont(ofSize: 14)
5
6let text = NSMutableAttributedString(
7    string: "x2",
8    attributes: [.font: baseFont]
9)
10
11text.addAttributes(
12    [
13        .font: superscriptFont,
14        .baselineOffset: 8
15    ],
16    range: NSRange(location: 1, length: 1)
17)

If you apply only .baselineOffset and leave the font size unchanged, the result often looks too large and awkward. The smaller font is part of what makes the text read as superscript or subscript rather than simply misaligned.

A Reusable Helper for UIKit

If you need this in several screens, move the logic into a helper instead of repeating attributed-string code inside view controllers.

swift
1import UIKit
2
3func makeStyledText(
4    text: String,
5    targetRange: NSRange,
6    baseFont: UIFont,
7    adjustedFont: UIFont,
8    offset: CGFloat
9) -> NSAttributedString {
10    let result = NSMutableAttributedString(
11        string: text,
12        attributes: [.font: baseFont]
13    )
14
15    result.addAttributes(
16        [
17            .font: adjustedFont,
18            .baselineOffset: offset
19        ],
20        range: targetRange
21    )
22
23    return result
24}
25
26let formula = makeStyledText(
27    text: "CO2",
28    targetRange: NSRange(location: 2, length: 1),
29    baseFont: .systemFont(ofSize: 24),
30    adjustedFont: .systemFont(ofSize: 16),
31    offset: -6
32)

This keeps typography choices centralized and makes later design changes easier.

SwiftUI for Simpler Cases

In SwiftUI, you can compose multiple Text views with different font sizes and baseline offsets.

swift
1import SwiftUI
2
3struct FormulaView: View {
4    var body: some View {
5        Text("x")
6        + Text("2")
7            .font(.system(size: 14))
8            .baselineOffset(8)
9    }
10}

That works well for short labels, formulas, and units such as square meters. If you need many styled ranges in a longer paragraph, UIKit-style attributed strings can still be easier to manage even in a SwiftUI app.

Unicode Characters Are Limited

You can sometimes use precomposed Unicode characters such as ² or , and that is fine for a few isolated labels. The problem is coverage: the Unicode superscript and subscript sets are incomplete, inconsistent, and not suitable for general scientific or mathematical formatting.

Styled text is more flexible because:

  • you can use normal characters
  • you control font and spacing
  • you are not limited to the small subset of available Unicode glyphs

For anything beyond a tiny one-off label, attributed styling is usually the safer long-term approach.

Choosing Between UIKit and SwiftUI

The choice is mostly about context:

  • Use NSAttributedString when the view is UIKit-based or when you need fine-grained range styling.
  • Use SwiftUI Text composition for small, simple fragments.
  • If the text is dynamic and comes from model data, wrap the styling in a helper so the caller supplies content and the helper applies typography consistently.

Keeping the styling policy centralized matters more than the specific API.

Common Pitfalls

The most common mistake is moving the baseline without reducing the font size, which makes the result look like an alignment bug instead of superscript or subscript. Another is hard-coding one offset value and assuming it looks correct in every font, size, and Dynamic Type setting. Developers also overuse Unicode superscript and subscript characters and then discover that the needed symbols do not exist. Finally, careless NSRange handling can break when the source string contains complex Unicode characters and the ranges are not computed correctly.

Summary

  • In Swift, subscript and superscript are typically implemented with styled text.
  • Combine a smaller font with .baselineOffset for the best result.
  • Use negative offsets for subscript and positive offsets for superscript.
  • SwiftUI handles simple cases well, while NSAttributedString is better for range-heavy text.
  • Unicode characters are useful in small cases but too limited for general formatting.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.