Failable Initializers in Swift
A failable initializer in Swift is an initializer that can return nil if the initialization process fails. This is particularly useful when the initialization depends on certain conditions that might not always be met. Failable initializers are denoted by appending a question mark (?) to the init keyword.
import Foundation
struct Website {
let url: URL
init?(urlString: String) {
guard let url = URL(string: urlString) else {
return nil
}
self.url = url
}
}
if let website = Website(urlString: "https://www.example.com") {
print("Valid URL: \(website.url)")
} else {
print("Invalid URL string.")
}
Here, the initializer attempts to create a URL from the provided string and returns nil if the string is not a valid URL.
Benefits of Using Failable Initializers: