The first thing boring swift beginners is the weird
! marks in different positions. Sometimes they follow
as and followed by a class name such as
as? Int, and sometimes they are right behind a class name like
Int?. If you are not sure what Optional and Casting do in Swift(1.2), please check them out.
Let's start with a simple example where we have an explicitly defined valuable:
var str:String = "This is a single string" var stringToOptional = str as String? //success var stringToUnwrappedOptional = str as String! //success var stringToNSString = str as NSString //success
In the above examples, as they have nothing to do with down-casting or up-casting, we don't need to use
as!, otherwise warning will be given. If the value of the
str is not initialised, the new/target valuable has to be Optional:
var str:String! var stringToOptional = str as String? //success var stringToUnwrappedOptional = str as String! //run-time error
Now when it comes to the cases where
as! play their roles:
var dic:Dictionary<String, AnyObject> = ["key": "Value in the dictionary"] //as? var anyObjectOptionalCastingToString = dic["key"] as? String // => "Value in the dictionary" var anyObjectOptionalCastingToInt = dic["key"] as? Int // nil //as! var anyObjectForceCastingToString = dic["key"] as! String // => "Value in the dictionary" var anyObjectForceCastingToInt = dic["key"] as! Int // run-time error
To summarise when we should use which:
String? - when we allow a valuable to be nil.
String! - when we allow a valuable to be nil and ready for use its value without appending "!"
as? - when we do casting but are not sure if the casting will be successful
as! - when we do casting and are very sure the casting goes successfully