An abstract class that declares an interface for objects that create, interpret, and validate the textual representation of values.


class Formatter : NSObject


Subclassing Notes

NSFormatter is intended for subclassing. A custom formatter can restrict the input and enhance the display of data in novel ways. For example, you could have a custom formatter that ensures that serial numbers entered by a user conform to predefined formats. Before you decide to create a custom formatter, make sure that you cannot configure the public subclasses to satisfy your requirements.

For instructions on how to create your own custom formatter, see Creating a Custom Formatter.


Getting Textual Representations of Object Values

func string(for: Any?) -> String?

The default implementation of this method raises an exception.

func attributedString(for: Any, withDefaultAttributes: [NSAttributedString.Key : Any]?) -> NSAttributedString?

The default implementation returns nil to indicate that the formatter object does not provide an attributed string.

func editingString(for: Any) -> String?

The default implementation of this method invokes string(for:).

Getting Object Values for Textual Representations

Validating Partial Strings

func isPartialStringValid(AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange: NSRangePointer?, originalString: String, originalSelectedRange: NSRange, errorDescription: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool

This method should be implemented in subclasses that want to validate user changes to a string in a field, where the user changes are not necessarily at the end of the string, and preserve the selection (or set a different one, such as selecting the erroneous part of the string the user has typed).


enum Formatter.Context

The formatting context for a formatter.

enum Formatter.UnitStyle

Specifies the width of the unit, determining the textual representation.


Inherits From

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software