Swift programming chapter 9 optionals issue with book code

I am getting a warning with this code from the book. Page 99

1 import Cocoa
2 var errorCodeString : String!
3 errorCodeString = “404”
4 print(errorCodeString)

i receive this warning…

Coercion of implicitly unwrappable value of type ‘String?’ to ‘Any’ does not unwrap optional

any help appreciated

An implicitly unwrapped optional is still an optional, so the print statement is going to print that it’s an optional unless you explicitly unwrap it. The warning is just letting you know that.

You can fix that a couple ways: either force unwrap the optional:

print(errorCodeString!)

or use the nil coalescing operator ?? (which they will talk about on page 102) to provide an alternate value to print if errorCodeString is nil:

print(errorCodeString ?? "No error")

You might be wondering what’s the point of having implicitly unwrapped optionals, then? Well, consider this code:

struct A {
    var x: Int
}
let a: A! = A(x: 1)
print(a.x) 

Notice I didn’t have to unwrap a there, I was able to say a.x rather than a!.x or a?.x. And since x is not an optional, I don’t get any warning messages about it.

PS: I’ll add this: I’ve been doing a bunch of Swift programming over the last few months solving Advent of Code puzzles - not iOS or MacOS apps, just command line programs - and so far I haven’t run into any use for implicitly unwrapped optionals. Plain old optionals, yes, but not the implicitly unwrapped variety. There may be something about GUIs that makes them useful, but in a more general sense I don’t see the need.

3 Likes

Implicitly unwrapped optionals are useful for declaring things that must always have valid values which can’t be provided at the point of declaration, and for eliminating the burden of optional unwrapping at the point of use.

Those values must be set somewhere else before any use of them can occur.

For example:

struct Globals {
    static var window        : NSWindow!
    static var controlCenter : ControlCenter!
    static var soundFiles    : [URL] = []
    static var configModel   : ConfigModel!
}
class AppDelegate: NSObject, NSApplicationDelegate {
    
    @IBOutlet var window: NSWindow!
    
    var controlCenter : ControlCenter!
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        Globals.window = window
    }

   ...
}
2 Likes