Adding in the ? or ! is making my code look messy and making me change everything after it.
Well, whether it's messy is quite subjective. Swift is designed this way to make you think about each optional you unwrap carefully. By doing this, you can avoid lots of those "unexpectedly found nil while unwrapping an optional value" errors.
Methods and properties return nil
for a reason. Usually the reason is that an error occurred, the thing couldn't be done, or there is no valid value for a property. You should think about these problems - "what should my method do if this method returns nil
?"
If you want to do something else when the value is nil
(i.e. it being nil is not fatal to your logic), use a if let
statement. e.g.
if let scaledCIImage = scaledImage?.ciImage {
// deal with the scaledCIImage
} else {
// do something else to remedy. The method can still continue running
}
If your method couldn't continue if the value is nil, then you can consider writing a guard statement:
guard let scaledCIImage = scaledImage?.ciImage else {
// you need to return some value or call "fatalError()" here
}
If you are absolutely sure that the value could not be nil, force unwrap it:
let scaledCIImage = scaledImage!.ciImage!
For the second error, you can fix it like:
// with force unwrapping
let filter = CIFilter(name: "CIAffineTile", withInputParameters:[kCIInputImageKey:scaledCIImage])!.outputImage!
// if let
if let filter = CIFilter(name: "CIAffineTile", withInputParameters:[kCIInputImageKey:scaledCIImage])?.outputImage {
// ...
}
// guard let
guard let filter = CIFilter(name: "CIAffineTile", withInputParameters:[kCIInputImageKey:scaledCIImage])?.outputImage else {
// ...
}
You can chain all of these together in a big if let
or guard let
statement like rmaddy has shown.