Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-03-26

Use those optional tuples

While converting some Objective-C code to Swift, I keep coming across the case where a function tests some parameters before it executes it's prime function. Very often in connection with the calculation of variables needed for its main purpose.

One example is this:

-(void)updateCursorPosition {
    
    // Check if there is a cursor position
    CharacterPosition* newCp = [datasource getCursorPosition];
    
    // If there is a new cp, always use it. If not, invalidate the current one.
    if (newCp != nil) {
        cursorPosition.lineIndex = newCp.lineIndex;
        cursorPosition.characterIndex = newCp.characterIndex;
    } else {
        [cursorPosition invalidate];
    }
    
    // Update the timer and make sure the cursor position remains visible
    if ([cursorPosition isValid]) {
        
        ....
    }

}

In Swift it is almost always possible to replace this verbose stuff with something much more simple, like this:

    func updateCursorPosition() {
        
        // Get the coordinates of a cursor position if there is just one
        
        if let (index, offset) = dataSource.getSingleCursorPosition() {
       
            ... prime functionality 
        }

    }

And in the datasource:

    func getSingleCursorPosition() -> (index: Int, offset: CGFloat)? {
        
        ... determine the insertion point

        if insertionPointFound {
           return (insertionPointIndex, insertionPointOffset)
        } else {
           return nil
        }
    }


While this is not an exact one to one mapping, functionally it is identical in my code. (Some other restructuring -using optionals- removes the need to invalidate the old cursor position)

This code snip shows the power of the optional tuple return value. Instead of some verbose logic that obscures the flow of the real purpose of the function, it is now possible to add just one function call that performs all this stuff.

Did I say that I like Swift? :-)

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment