There are two types of variables in Swift.
- Optional Variables
- Normal(Non-Optional) Variables
Optional Variables:
The shortest description is Optional variables/objects contains the the property "object-returns-nil-when-non-exist". In objC almost all the object we create is optional variable only. That is the objects has the property "object-returns-nil-when-non-exist" behavior. However, this particular behavior is not needed all the time. So, to identify the optionals the symbols '?' and '!' has been used. Again there are two type of optionals...
- Normal Optionals(?)
- Implicitly unwrapped optionals(!)
Normal optionals:
var normalOptional : String?
Implicitly unwrapped optionals:
var specialOptional : String!
Both are having the "optional" behaviour, but the difference is the 'Implicitly unwrapped optional' can also be used as a normal(non-optional) value.
For instance, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list by default tableview delegate methods. The row value exists when the cellForRowAtIndex is get called. There, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list.
So, the unwrapping of 'row' value from 'indexPath' is as follows.
var rowValue = indexPath?.row // variable rowValue inferred as optional Int value
or
var rowValue = indexPath!.row// variable rowValue inferred as normal Int value
Note: When using the '!' unwrapping, have to be very sure that the particular class exists(contains value).
Hope this link will gives you more idea. What is the intended use of optional variable/constant in swift