NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
Quick Tip Icon
Quick Tip

Copy a string to the clipboard in Swift on macOS

I’ve been implementing copy-to-clipboard functionality in a Mac app and realized that it’s a bit different from iOS. With UIPasteboard, assigning a string automatically replaces the previous contents of the clipboard with the new string. But on macOS, we need to clear the previous contents manually, otherwise, it won’t work.

So essentially, to copy a string to the clipboard on macOS, our code will look like this:

func copyToClipboard(string: String) {
    let pasteboard = NSPasteboard.general
    pasteboard.clearContents()
    pasteboard.setString(string, forType: .string)
}

We should use clearContents() as the first step when providing data to the pasteboard.

I found a few solutions online suggesting the use of declareTypes(_:owner:) as the initial step for setting up the pasteboard. However, according to Apple’s documentation for NSPasteboard, this approach was meant for writing data to the pasteboard on macOS versions 10.5 and earlier.


If you're an experienced Swift developer looking to deepen your skills, my book Swift Gems covers advanced techniques like optimizing collections, handling strings, and mastering asynchronous programming, perfect for taking your Swift expertise to the next level.

For more resources on Swift and SwiftUI, check out my other books and book bundles.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35