skip to Main Content

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

Answers


  1. you could try this:

    init() {
        if let paste = NSPasteboard.general.string(forType: .string) {
            // do something with paste
        } else {
            // do something when paste is nil
        }
        ....
    }
    
    Login or Signup to reply.
  2. if let _ = NSPasteboard.general.data(forType: .string) {
        print("You have data")
    } else {
        print("Oops, you don't.")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search