Blog

Filtering objects to Optionals

17 Jun, 2016
Xebia Background Header Wave

A while ago I stumbled upon a Blog post by Natascha the Robot about Configuring a Constant Using Shorthand Argument Names in Swift. Which by itself is a great post, but I was most inspired by the Then library mentioned at the end of her post. Seeing how such a small amount of code could change the way we configure constants everywhere gave me the idea to create something in a very similar fashion. But instead of configuring a variable it’s used to filter one based on a condition. Because why should filter only be applicable to collection types?

The usage of it is extremely simple and very useful:

extension String: Filter {}
"12345".filter { $0.characters.count > 4 } // Optional("12345")
"12".filter { $0.characters.count > 4 } // Optional(nil)

Only very little code is required to make this work:

extension Filter {
    /// Allows filtering of non sequence types.
    ///
    ///     let label = UILabel().then {
    ///         $0.textAlignment = .Center
    ///         $0.textColor = UIColor.blackColor()
    ///         $0.text = "Hello, World!"
    ///     }
    public func filter(@noescape condition: Self -> Bool) -> Self? {
        return condition(self) ? self : nil
    }
}
extension NSObject: Filter {}

Not enough code to make a library out of it in my opinion. Just copy this code into your project. I did create a GitHub Gist which I will update if needed.

With this code, any object that inherits from NSObject will work by default. For pure Swift objects, just add the one liner to let the object adhere to the Filter protocol.

I’d love to hear your comments and hear about alternatives to this.

Questions?

Get in touch with us to learn more about the subject and related solutions

Explore related posts