Sorry, I wasn’t saying that you shouldn’t have posted about that line of code, I was just trying to join both our posts with a link. When I was copying the code in the book, I tried to do it from memory, and I wrote the code in my program as:
name = aDecoder.decodeObjectForKey("name) as? String
Then I spent a little while trying to determine why the book used:
name = aDecoder.decodeObjectForKey("name) as! String?
Early on in the book, I couldn’t understand the optionals used in the examples, and I posted about them, but I eventually came to realize that the book just uses the unsafe ! whenever there is an optional, which I interpret to mean, “We want the program to fail here if the value is nil”.
The name variable was declared as type String?, so it seems reasonable to cast the right hand side of the assignment to the type String?. But when I write this:
[code]func doStuff(x: Int) → AnyObject? {
if x==2 {
return “Jim”
}
else {
return nil
}
}
var name: String?
name = doStuff(2) as? String?
[/code]
…in the assignment statement, I think I am saying, “Cast the return value of doStuff(2) to the type String? and if that cast can’t be done, then return nil.” But Xcode immediately flags that with the error:
What?? You mean String?? is a type? What the?! Let’s try it:
var name: String??
name = doStuff(2) as? String?
println(name)
--output:--
Optional(Optional("Jim"))
Oh, boy.
In any case, the reason for the ! in the original example may be as simple as: "The authors tried as? but Xcode indicated that was an error and asked the authors if they wanted to change it to as!.