Silver Challenge Solution Help

This chapter was pretty heavy. Does anyone have a solution to this challenge? The book says accessing an optional’s value when it is nil will result in runtime. I thought it only does that when we use !.

Make this mistake by force-unwrapping an optional when it is nil

You’re right! Force unwrap a nil String? and take a look at what the error is.

Experiment with the following code, but understanding it fully requires familiarity with enums, generic data types, and the Optional type. So you may have to visit here again after you have become familiar with those types.

main.swift

ForcedUnwrap.main ()

ForcedUnwrap.swift

//
//  ForcedUnwrap.swift
//
//  SwiftMatters
//
//  Created by ibex10 on 9/8/17.
//
//  Copyright © 2017 SwiftMatters. All rights reserved.
//

import Foundation

struct ForcedUnwrap {
    static func main () {

        // Unwrap this optional
        let x : Int? = nil
        
        // Forced unwrap
        if case .some = x {
            print ("x: \(x!)")
        }
        else /* if case .none = x */ {
            print ("x: not set")
        }
        
        // Unwrap
        if case .some (let v) = x {
            print ("x: \(v)")
        }
        else /* if case .none = x */ {
            print ("x: not set")
        }
        
        // Unwrap if set or use a default if not set
        let v = x ?? 0
        print ("x: \(v)")
        
        // Forced unwrap or die if not set
        let u = x!
        print ("x: \(u)")
    }
}

I just did this:

var myMistake: String?
let BOOM = myMistake!

The main part of the error is “error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION . . . .” My rudimentary understanding of it is that the “let” instruction tells the system to obtain the bits assigned to myMistake and assign those to BOOM, but there are no bits assigned yet, so your program throws a binary hissyfit. Remove the forced unwrapping (!) and all is good.