Created
February 8, 2016 22:21
-
-
Save kristopherjohnson/fc3082daf54c3de31ec0 to your computer and use it in GitHub Desktop.
Value transformer that returns true for strings that are non-empty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| /// Given a `String?`, return an `NSNumber` Boolean value that is true if the value is non-nil and not empty. | |
| /// | |
| /// This is useful for binding the `enabled` property of a button to a string value that is bound to a text field. | |
| final class IsNotNilOrEmptyValueTransformer: NSValueTransformer { | |
| override class func transformedValueClass() -> AnyClass { | |
| return NSNumber.self | |
| } | |
| override class func allowsReverseTransformation() -> Bool { | |
| return false | |
| } | |
| override func transformedValue(value: AnyObject?) -> AnyObject? { | |
| guard let stringValue = value as? String else { return NSNumber(bool: false) } | |
| return NSNumber(bool: !stringValue.isEmpty) | |
| } | |
| class func registerValueTransformer() { | |
| let instance = IsNotNilOrEmptyValueTransformer() | |
| NSValueTransformer.setValueTransformer(instance, forName: "IsNotNilOrEmptyValueTransformer") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment