Swift ui xcode NSPasteboard empty

224 views Asked by At

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)!
...
}
2

There are 2 answers

0
workingdog support Ukraine On BEST ANSWER

you could try this:

init() {
    if let paste = NSPasteboard.general.string(forType: .string) {
        // do something with paste
    } else {
        // do something when paste is nil
    }
    ....
}
0
El Tomato On
if let _ = NSPasteboard.general.data(forType: .string) {
    print("You have data")
} else {
    print("Oops, you don't.")
}