-2
var neilPeart: Drummer? = Drummer()

var rush: Band? = Band(drummer: neilPaert!)

Suppose we have an instance named neilPeart of optional type of Drummer, and an instance named rush of optional type of Band. There is a band property for Drummer instances. If I want to change the band property of neilPeart, what's the difference between "neilPeart?.band = rush" and "neilPeart!.band = rush"

  • 1
    ? means object can be nil ahead, ! means it must have a assigned value. – vaibhav Jul 27 '17 at 04:49
  • `neilPeart?.band` won't crash if `neilPeart` was `nil`. The other, using `!` would crash. See [How is if let evaluated](https://stackoverflow.com/a/38041086/5175709) – mfaani Jul 27 '17 at 04:50
  • 5
    Reading up on basic Swift documentation could help a lot here... – Jerrybibo Jul 27 '17 at 04:53
  • 1
    See this [answer](https://stackoverflow.com/a/24583157/3687801) – nayem Jul 27 '17 at 05:09
  • 1
    Possible duplicate of [Why create "Implicitly Unwrapped Optionals"?](https://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals) – nayem Jul 27 '17 at 05:10

2 Answers2

2
  • ? will set it to nil if there is no value
  • ! will force unwrap the value and will crash the app if there is no value
Andrew
  • 43
  • 6
2

Optionals use ? marks which means that if I were to say var title: String?. That would mean that title could either contain a value or be nil. The ! points are used to unwrap an optional value. This could create an issue for you and give you an error if your value is nil. The error would result in not being able to unwrap a nil object. Hope this helps!

Rajat Khare
  • 522
  • 8
  • 26