Last active
August 24, 2020 03:44
-
-
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
This file contains 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 | |
/// 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) | |
} | |
} |
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
You must register this value transformer ONCE before using. Usually this is done the initialisation of your app (for example, in
applicationDidFinishLaunching
.