swiftswift4

what is the difference between "?" and "!" operator in swift?


I was just wondering what is the difference between "?" and "!" in swift, I'm new to swift. I tried looking for questions similar in here, but couldn't find any.


Solution

  • An optional type can be nil

    var nameOfToy: String?
    

    The toy may have a name;

    nameOfToy = "Buzz"
    

    so

    print (nameOfToy!)
    

    is Buzz.

    The question mark indicates that it is optional, i.e. can be nil, so you have to UNWRAP it with the !. This is because the variable is optional.

    But what happens if there is no name of a toy, and you use !. In this case you get a nasty crash.