Failable initializers in Swift:
Failable initializers in Swift is an initializer that can return nil to indicate that the initialization process has failed.
Failable initializers are declared using the init?
keyword.
They are commonly used when the initialization of an object might not be successful due to certain conditions or invalid parameters.
Here’s a simple example of a failable initializer:
struct User { let name: String let age: Int init?(name: String, age: Int) { if age < 0 { return nil } self.name = name self.age = age } } let validUser = User(name: "Sid", age: 26) // User(name: "Sid", age: 26) let inValidUser = User(name: "Sim", age: -1) // nil // Usage of the failable initializer if let user = User(name: "Sid", age: 26) { print("User Details: \(user.name), \(user.age)") } else { print("Invalid User") }
Here Person
struct is an example of a failable initializer
. It’s designed to create a Person
instance with a given name
and age
, but it returns nil
if the provided age
is less than 0. This is a reasonable use of a failable initializer
to handle the case where the initialization may fail due to invalid input.