Swift: Detecting an Unexpected Nil Value in a Non-Optional at Runtime: Casting as Optional Fails

Best way to check non-optional values for nil in Swift

Even Apple's APIs sometimes return nil for a type that is not marked in the API as Optional. The solution is to assign to an Optional.

For example, for a while traitCollectionDidChange returned a UITraitCollection even though it could in fact be nil. You couldn't check it for nil because Swift won't let you check a non-Optional for nil.

The workaround was to assign the returned value immediately to a UITraitCollection? and check that for nil. That sort of thing should work for whatever your use case is as well (though your mail example is not a use case, because you're doing it wrong from the get-go).

Swift - casting a nil core data string as an optional value

It looks like what you really want is this:

if object.metadata != nil {
...
}

or this:

if let metadata = object.metadata as? String {
// You can now freely access metadata as a non-optional
...
}

--EDIT--

My mistake, I didn't read the first part of your question thoroughly enough. It looks like the duplicate answer has a solution for this. Essentially, the generated managed object subclass is a bug and you should modify the properties to be either optional or implicitly unwrapped. You can check both of those using the first method for implicitly unwrapped and second for optionals.

There are several questions which discuss the issue of the generated subclasses not producing optional properties. I wouldn't be too concerned about editing the subclasses; there's nothing special about them except that Apple is making it easier to create them.

Check if property is set in Core Data?

Swift + CoreData: Cannot Automatically Set Optional Attribute On Generated NSManagedObject Subclass

--Edit2--

If you really don't want to touch the subclass you can access the property using valueForKey() and could add that as an extension if you wanted something a bit cleaner.

if let metadata = object.valueForKey("metadata") as String? {
...
}

In an extension:

extension ObjectClass {
var realMetadata: String? {
set {
self.setValue(newValue, forKey: "metadata")
}
get {
return self.valueForKey("metadata") as String?
}
}
}

Can I check if an optional is nil by using it as an argument?

You can use the

public func flatMap<U>(_ transform: (Wrapped) throws -> U?) rethrows -> U?

method of Optional:

if let parsedZoomURL = zoomURL.flatMap( { URL(string: $0) }) {
//do stuff
}

or shorter (as someone noticed in a now deleted comment):

if let parsedZoomURL = zoomURL.flatMap(URL.init) {
//do stuff
}

The optional binding succeeds only if zoomURL is not nil
and the closure (which is then called with the unwrapped value
of zoomURL) does not return nil.

Fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

Such errors occur when you attempt to access the value of a variable declared as an 'Implicitly Unwrapped Optional' (that is, declared with a !) but when that variable is unbound (bound to nil).

In your case, the crash occurs because in a UITableViewController the tableView property is defined as:

var tableView: UITableView!

It is an implicitly unwrapped optional. If it is unbound, crash.

You've not bound tableView within Xcode's Interface Builder to your UITableViewController. In Xcode, if you look at your controller in the 'Connections Inspector' you will find under 'Outlets' that 'view' is not bound. Thus, the expression self.tableView will produce a runtime crash.

Swift optional parameter not unwrapped

There are a few ways to code this properly:

func addEntry(text: String, position: Int?) {
// Safely unwrap the value
if let position = position {
entries[position] = text
} else {
entries.append(text)
}
}

or:

func addEntry(text: String, position: Int?) {
if position == nil {
entries.append(text)
} else {
// Force unwrap since you know it isn't nil
entries[position!] = text
}
}

Checking for 'nil' does not work

Optional(<null>) in the output suggests that it's actually NSNull.

You may replace

if typeSpecifier != nil

with

if !typespecifier is NSNull


Related Topics



Leave a reply



Submit