How can I validate a string is an email address?
Asked on 2024-07-30
1 search
To validate a string as an email address, you can use regular expressions (regex) in Swift. Here's a simple example of how you can do this:
import Foundation
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
// Example usage
let email = "example@domain.com"
print(isValidEmail(email)) // true or false
This function uses a regular expression to check if the input string matches the pattern of a typical email address. The NSPredicate class is used to evaluate the string against the regex pattern.
For more advanced error handling and validation techniques in Swift, you might find the sessions on Swift testing useful:
These sessions cover various aspects of testing and validation in Swift, which can help you ensure your code handles errors gracefully and behaves as expected.

A Swift Tour: Explore Swift’s features and design
Learn the essential features and design philosophy of the Swift programming language. We’ll explore how to model data, handle errors, use protocols, write concurrent code, and more while building up a Swift package that has a library, an HTTP server, and a command line client. Whether you’re just beginning your Swift journey or have been with us from the start, this talk will help you get the most out of the language.

Go further with Swift Testing
Learn how to write a sweet set of (test) suites using Swift Testing’s baked-in features. Discover how to take the building blocks further and use them to help expand tests to cover more scenarios, organize your tests across different suites, and optimize your tests to run in parallel.

Unlock the power of places with MapKit
Discover powerful new ways to integrate maps into your apps and websites with MapKit and MapKit JS. Learn how to save and reference unique places using Place ID. Check out improvements to search that make it more efficient to find relevant places. Get introduced to the new Place Card API that lets you display rich information about places so customers can explore destinations right in your app. And, we’ll show you quick ways to embed maps in your website with our simplified token provisioning and Web Embed API.
