Member-only story

Implementing A Custom Formatter in Swift

Validate and format displayed and user input values conveniently.

Gabriel Theodoropoulos
7 min readFeb 4, 2022
Photo by hosein ashrafosadat from Pexels

When implementing apps that contain fields or views with values of various types, we soon come to a point where it becomes necessary to format appropriately when representing them visually. It’s part of the job to display all that as much as user-friendly as possible, and provide an actual information; not just mere data. Think, for example, of a text field that allows users to edit currency values. Displaying a currency symbol along with the actual amount is important. Not only it increases the overall user experience, but it also makes it instantly clear what the meaning of that number is.

Swift provides a few formatters that allow to properly format the textual representation of values in text fields or text views. A collection of them can be found in this official documentation page. However, there are often cases where no built-in formatters exist to format the displayed values as needed. There is an alternative in those circumstances; to create our own custom formatters.

The recipe to implement a custom formatter is relatively simple. The first step is to define a new type (class) that will be inheriting from the Formatter class; that is the Swift version of NSFormatter which comes from Objective-C. After…

--

--

Gabriel Theodoropoulos
Gabriel Theodoropoulos

Written by Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

No responses yet