Swift
clipboard
pasteboard
iOS development
programming tutorial

How to copy text to clipboard/pasteboard with Swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Copying text to the clipboard on Apple platforms is technically simple, but a production-quality implementation should still validate input and respect privacy. On iOS and iPadOS, UIPasteboard is the standard API, and it works best when wrapped in a small reusable abstraction instead of being called ad hoc from many screens.

Use UIPasteboard.general for Basic Copy

The simplest possible copy action is assigning a string to the general pasteboard.

swift
import UIKit

UIPasteboard.general.string = "INV-2026-0042"

That is enough for a prototype. In a real app, you usually want to avoid copying empty strings, placeholder values, or sensitive text without an explicit user action.

Wrap Clipboard Access in a Service

A small wrapper makes the behavior consistent across the app.

swift
1import UIKit
2
3protocol ClipboardProviding {
4    func copy(text: String)
5    func readText() -> String?
6}
7
8final class SystemClipboard: ClipboardProviding {
9    func copy(text: String) {
10        UIPasteboard.general.string = text
11    }
12
13    func readText() -> String? {
14        UIPasteboard.general.string
15    }
16}

This gives you one place to add trimming, logging, or policy checks later.

UIKit Example With Validation and Feedback

A copy button should ignore empty values and confirm success to the user.

swift
1import UIKit
2
3final class AccountViewController: UIViewController {
4    @IBOutlet private weak var accountIdLabel: UILabel!
5    private let clipboard: ClipboardProviding = SystemClipboard()
6
7    @IBAction private func copyButtonTapped(_ sender: UIButton) {
8        let value = accountIdLabel.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
9        guard !value.isEmpty else { return }
10
11        clipboard.copy(text: value)
12        presentCopiedBanner()
13    }
14
15    private func presentCopiedBanner() {
16        let alert = UIAlertController(title: "Copied", message: "Account ID copied", preferredStyle: .alert)
17        present(alert, animated: true)
18        DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
19            alert.dismiss(animated: true)
20        }
21    }
22}

That feedback step matters. Without it, users often tap again because the interface gave no sign the copy operation worked.

SwiftUI Uses the Same API

SwiftUI can still call UIPasteboard directly from an action closure.

swift
1import SwiftUI
2import UIKit
3
4struct CopyCodeView: View {
5    let code: String
6    @State private var copied = false
7
8    var body: some View {
9        VStack(spacing: 12) {
10            Text(code)
11                .font(.system(.body, design: .monospaced))
12
13            Button("Copy code") {
14                let trimmed = code.trimmingCharacters(in: .whitespacesAndNewlines)
15                guard !trimmed.isEmpty else { return }
16                UIPasteboard.general.string = trimmed
17                copied = true
18
19                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
20                    copied = false
21                }
22            }
23
24            if copied {
25                Text("Copied")
26                    .foregroundColor(.green)
27            }
28        }
29        .padding()
30    }
31}

If your app already has a shared architecture layer, use the same clipboard service from SwiftUI rather than scattering pasteboard writes through view code.

Copy Other Types When Appropriate

The pasteboard can store more than plain text. If you have a URL, use the URL property instead of converting it to a string first.

swift
import UIKit

UIPasteboard.general.url = URL(string: "https://example.com/support")

Using the most specific type available makes paste behavior more predictable in other apps.

Treat the Clipboard as Shared State

The system pasteboard is visible outside your app. That means copy actions have privacy implications.

Good rules include:

  • do not auto-copy secrets without explicit user action
  • trim accidental whitespace before copying
  • think carefully before copying tokens, passwords, or one-time codes
  • document any feature that reads pasteboard content automatically

Clipboard behavior is not just a UI detail. It is part of the app's trust model.

Common Pitfalls

The most common mistake is copying empty or placeholder text because the source value was never validated.

Another common issue is giving no feedback after the copy action. Developers also sometimes treat the clipboard as harmless temporary storage and forget that other apps and the system can observe or replace pasteboard contents after the copy occurs.

Summary

  • Use UIPasteboard.general for standard copy-to-clipboard behavior on iOS.
  • Wrap pasteboard access in a small service when several screens need copy behavior.
  • Trim and validate text before copying it.
  • Give the user visible confirmation that the copy succeeded.
  • Treat the pasteboard as shared state and be careful with sensitive data.

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.