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.