Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save kristopherjohnson/fc3082daf54c3de31ec0 to your computer and use it in GitHub Desktop.

Select an option

Save kristopherjohnson/fc3082daf54c3de31ec0 to your computer and use it in GitHub Desktop.
Value transformer that returns true for strings that are non-empty
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