-5

I have this doubt when I run this code both of them give me the same datatype as result. I know I am missing something really basic can someone please explain why ! and ? on a type gives the same datatype as result?

import UIKit
import Foundation

var unwrappedString: String!
var optionalString: String?

print("type of unwrappedString is:", type(of:unwrappedString))
print("type of optionalString is:", type(of:optionalString))

output is

type of unwrappedString is: Optional<String>
type of optionalString is: Optional<String>
thndrkiss
  • 4,515
  • 8
  • 57
  • 96

1 Answers1

2

Both symbols ! and ? used for optionals. We should have to use !, when we make sure option type variable has value at a time and we need to take action on it. Otherwise it will crash if variable value is nil nd if you are using ?, Application will not crash in nil case.

Cristik
  • 30,989
  • 25
  • 91
  • 127
Vipin Pareek
  • 236
  • 2
  • 10
  • SE-0054 cleared my doubt – thndrkiss Apr 16 '20 at 08:34
  • ```We should have to use !``` — you SHOULD NOT use `!` at all, unless you're interacting with some ObjC libraries that do some behind-the-scene late initialisation(like Interface Builder). In you own code you should use either proper optionals, or just non-optional. – user28434'mstep Apr 16 '20 at 08:38
  • @user28434'mstep there are legitimate cases for using `!`, let's not take it to the extreme. – Cristik May 18 '22 at 07:49
  • @Cristik, only for the late initialization. And with @propertyWrapper even this case can be replaced with a neat wrapper. In all other cases: if we know that it won't be `nil` — just unwrap in `T`, if we don't know if it would be `nil` (and it can go back and forth betwee `.some` and `.none`) — just use `T?`. `T!` is just a crutch that shouldn't be in the language from the time they started designing it. – user28434'mstep May 19 '22 at 08:08