Filtering objects to Optionals

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.

Uncovering the mysteries of Swift property observers

One of the cool features of Swift are property observers, perhaps better known as the willSet and didSet. Everyone programming in Swift must have used them. Some people more than others. And some people might use them a little bit too much, changing many of them together (me sometimes included). But it’s not always completely obvious when they are called. Especially when dealing with struct, because structs can be a bit odd. Let’s dive into some situations and see what happens.

Read more →

Add ifPresent to Swift Optionals

In my previous post I wrote a lot about how you can use the map and flatMap functions of Swift Optionals. In this one, I'll add a custom function to Optionals through an extension, the ifPresent function.

extension Optional {

    public func ifPresent(@noescape f: (Wrapped) throws -> Void) rethrows {
        switch self {
        case .Some(let value): try f(value)
        case .None: ()
        }
    }
}

Read more →

The power of map and flatMap of Swift optionals

Until recently, I always felt like I was missing something in Swift. Something that makes working with optionals a lot easier. And just a short while ago I found out that the thing I was missing does already exist. I'm talking about the map and flatMap functions of Swift optionals (not the Array map function). Perhaps it's because they're not mentioned in the optionals sections of the Swift guide and because I haven't seen it in any other samples or tutorials. And after asking around I found out some of my fellow Swift programmers also didn't know about it. Since I find it an amazing Swift feature that makes your Swift code often a lot more elegant I'd like to share my experiences with it.

If you didn't know about the map and flatMap functions either you should keep on reading. If you did already know about it, I hope to show some good, real and useful samples of it's usage that perhaps you didn't think about yet.

Read more →

Simplification of iOS View Controllers: MVVM or Presentation Controls?

We've all seen View Controllers consisting of hundred or even thousands of lines of code. One popular strategy of reducing view controller complexity is using the Model-View-ViewModel (MVVM) design pattern. But that's not the only way to separate the view controllers into smaller, easier to understand components. This post will explore using small Presentation Control classes to achieve a similar effect. They can even be used together with MVVM components.

Read more →

Parallax image scrolling using Storyboards

Parallax image scrolling is a popular concept that is being adopted by many apps these days. It's the small attention to details like this that can really make an app great. Parallax scrolling gives you the illusion of depth by letting objects in the background scroll slower than objects in the foreground. It has been used in the past by many 2d games to make them feel more 3d. True parallax scrolling can become quite complex, but it's not very hard to create a simple parallax image scrolling effect on iOS yourself. This post will show you how to add it to a table view using Storyboards.

Read more →

Understanding the 'sender' in segues and use it to pass on data to another view controller

One of the downsides of using segues in storyboards is that you often still need to write code to pass on data from the source view controller to the destination view controller. The prepareForSegue(_:sender:) method is the right place to do this. Sometimes you need to manually trigger a segue by calling performSegueWithIdentifier(_:sender:), and it's there you usually know what data you need to pass on. How can we avoid adding extra state variables in our source view controller just for passing on data? A simple trick is to use the sender parameter that both methods have.

Read more →