Lucas Adam Lucas Adam - 10 days ago 6x
Swift Question

NSCoding : Found nil unwrapping an Optional value

since updating to Swift 3 I get this very known crash that I'm not able to solve by myself... :

fatal error: unexpectedly found nil while unwrapping an Optional value* :

on line

self.isDefault = aDecoder.decodeObject(forKey: "BoxUserDefault_isDefault") as! Bool

Why would it crash now ?

Here's my class

class BoxUserDefault: NSObject, NSCoding {

var frendlyName: String
var hostname: String
var isDefault: Bool

init(frendlyName: String, hostname: String, isDefault: Bool) {
self.frendlyName = frendlyName
self.hostname = hostname
self.isDefault = isDefault

func encode(with aCoder: NSCoder) {
aCoder.encode(self.frendlyName, forKey: "BoxUserDefault_frendlyName")
aCoder.encode(self.hostname, forKey: "BoxUserDefault_hostname")
aCoder.encode(self.isDefault, forKey: "BoxUserDefault_isDefault")

required init?(coder aDecoder: NSCoder) {
self.frendlyName = aDecoder.decodeObject(forKey: "BoxUserDefault_frendlyName") as! String
self.hostname = aDecoder.decodeObject(forKey: "BoxUserDefault_hostname") as! String
self.isDefault = aDecoder.decodeObject(forKey: "BoxUserDefault_isDefault") as! Bool


Any idea ? thanks guys


Use the appropriate method decodeBool(forKey:

self.isDefault = aDecoder.decodeBool(forKey: "BoxUserDefault_isDefault")!