Skip to content

Instantly share code, notes, and snippets.

@dagronf
Last active August 24, 2020 03:44
Show Gist options
  • Save dagronf/671b9fe9d955efc4e319486e0f37eff5 to your computer and use it in GitHub Desktop.
Save dagronf/671b9fe9d955efc4e319486e0f37eff5 to your computer and use it in GitHub Desktop.
Swift Value transformer that returns true if the value is a non empty string or false otherwise
import Foundation
/// Value transformer that returns NSNumber(true) if the value is a non empty string or NSNumber(false) otherwise
@objc public class IsEmptyStringValueTransformer: ValueTransformer {
// Public name to use in interface builder
private static let name = NSValueTransformerName(rawValue: "IsEmptyStringValueTransformer")
// Shared value transformer instance
@objc static public var shared = ValueTransformer(forName: IsEmptyStringValueTransformer.name)
/// Call to register the value transformer. Must be called at least ONCE during initialization of your code
@objc static public func Register() {
ValueTransformer.setValueTransformer(
IsEmptyStringValueTransformer(),
forName: IsEmptyStringValueTransformer.name)
}
@objc public override class func transformedValueClass() -> AnyClass {
return NSNumber.self
}
@objc public override class func allowsReverseTransformation() -> Bool {
return false
}
@objc public override func transformedValue(_ value: Any?) -> Any? {
guard let str = value as? String else {
// Unfortunately we cannot tell whether a nil value is of a certain
// type. So if it's nil, assume that its an empty string
return true
}
return NSNumber(value: str.isEmpty)
}
}
@dagronf
Copy link
Author

dagronf commented Aug 24, 2020

You must register this value transformer ONCE before using. Usually this is done the initialisation of your app (for example, in applicationDidFinishLaunching.

func applicationDidFinishLaunching(_: Notification) {
    IsEmptyStringValueTransformer.Register()
}

@dagronf
Copy link
Author

dagronf commented Aug 24, 2020

And use the name IsEmptyStringValueTransformer in Interface Builder (for example, to hide a text field if there's no content in it via bindings)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment