As document said “you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!)”
So why UIViewController init method use
init(nibName nibName: String!,bundle nibBundle: NSBundle!)
and tell me "If you specify nil, the nibName property is set to nil."
Why not use init(nibName nibName: String?,bundle nibBundle: NSBundle?)
instead?
I am so confused about this.
From my understanding ?
is used to indicate an optional variable. !
is used to access the value of an optional variable. Document says
“Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!)”
That means use !
only if you are sure it has a non nil value otherwise it will throw error. Its like forcing an optional variable to have value.
Then about your question
init(nibName nibName: String!,bundle nibBundle: NSBundle!)
Here the init function is forcing the caller to pass the values for nibName
and nibBundle
. It cannot be nil. !
is used to make sure that the parameters has a non nil value
Note: If iam wrong please correct me, iam just learnig:)
!
is a pure syntactic sugar. The variable is still an optional; you can use it as a normal optional, passing nil
, etc. It's only necessary so that you can simplify to nibName
rather than use the full nibName!
Source—
“These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (
String!
) rather than a question mark (String?
) after the type that you want to make optional.” ...“An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it is accessed. ”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With