Given the following in Swift:
var optionalString: String?
let dict = NSDictionary()
What is the practical difference between the following
as? Types
- means the down casting process is optional. The process can be successful or not(system will return nil if down casting fails).Any way will not crash if down casting fails.
as! Type?
- Here the process of down casting should be successful (!
indicates that) . The ending question mark indicates whether final result can be nil or not.
More info regarding "!" and "?"
Let us take 2 cases
Consider:
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
Here we don't know whether the result of down casting of cell with identifier "Cell" to UITableViewCell is success or not. If unsuccessful then it returns nil( so we avoid crash here). Here we can do as given below.
if let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell {
// If we reached here it means the down casting was successful
}
else {
// unsuccessful down casting
}
So let us remember it like this - If ?
it means we are not sure whether value is nil or not (question mark comes when we don't know things).
Contrast that to:
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell.
Here we tell the compiler that down casting should be successful. If it fails the system will crash. So we give !
when we are sure that value is non nil.