Using NSValueTransformers (Value Transformer) Swift 2.0

So here’s a tricky one, on my upcoming app I sometimes use View-Based TableViews.

Mostly, it works like magic, but sometimes you need to use a Value Transformer in the binding to allow the table to understand how to display something. In this example, I needed to convert a NSNumber to a String (and back!). Here’s how you do it:

1. Create a NSValueTransformer subclass (here’s mine for your reference):

import Cocoa

 

class TransformerNSNumberToString: NSValueTransformer {

 

    override class func transformedValueClass() -> AnyClass { //What do I transform

        return NSNumber.self

    }

    

    override class func allowsReverseTransformation() -> Bool { //Can I transform back?

        returntrue

    }

    

    override func transformedValue(value: AnyObject?) -> AnyObject? { //Perform transformation

        guard let type = value as? NSNumber else { return nil }

        return type.stringValue

        

    }

    

    override func reverseTransformedValue(value: AnyObject?) -> AnyObject? { //Revert transformation

        guard let type = value as? NSString else { return nil }

        return NSNumber(double: type.doubleValue)

    }

}

2. In the App Delegate, in my case I put it inside applicationDidFinishLaunching you add (yes, it’s weird but true!):

func applicationDidFinishLaunching(aNotification: NSNotification) {

        NSValueTransformer.setValueTransformer(TransformerNSNumberToString(), forName: “TransformerNSNumberToString”) //

    }

3. In the binding you add the Value Transformer needed!

Screen Shot 2016 02 07 at 21 32 28

Screen Shot 2016 02 07 at 21 32 36

 

That’s it! A great post explaining this in more detail is NSHipster, it’s the best source I found out there apart from Apple docs. 

Questions / comments? I’m at @MarcMasVi

Marc