How do I use clipboard and pasteboard on macOS using Swift?

In Swift for macOS, you can access the clipboard using the NSPasteboard class. Below is a simple example demonstrating how to copy text to the clipboard and then read it back.

// Access the general pasteboard let pasteboard = NSPasteboard.general // Set the string to the clipboard let textToCopy = "Hello, Clipboard!" pasteboard.clearContents() // Clear current contents pasteboard.setString(textToCopy, forType: .string) // Read the string back from the clipboard if let copiedText = pasteboard.string(forType: .string) { print("Copied text from clipboard: \(copiedText)") }

Swift NSPasteboard macOS clipboard pasteboard copy paste