Search code examples
swiftxcodeswiftuiclipboardnspasteboard

Swift ui xcode NSPasteboard empty


enter image description here

I have the following code at the beginning of the program, when it starts I need to see if there is any copied text.

But if I start the program and no text has been copied at the moment, I get the following error.

How can I solve the problem?

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
init() {
        let paste = NSPasteboard.general.string(forType: .string)!
...
}

Solution

  • you could try this:

    init() {
        if let paste = NSPasteboard.general.string(forType: .string) {
            // do something with paste
        } else {
            // do something when paste is nil
        }
        ....
    }