Failable initialisers in Swift, and their usage

  1. When validation of user input is required in a Signing option with a user name and password against any empty parameter, we can use a failable initializer.
// Validating user inputs

struct LoginForm {
let username: String
let password: String

init?(username: String, password: String) {
guard !username.isEmpty, !password.isEmpty else {
return nil
}

self.username = username
self.password = password
}
}

func login() {
if let loginForm = LoginForm(username: "Evangelist", password: "") {
print("login username = ", loginForm.username)
} else {
print("failed to initialize")
}
}
struct URL {
let urlString: String

init?(urlString: String) {
guard let url = Foundation.URL(string: urlString) else {
return nil
}
self.urlString = url.absoluteString
}
}
struct Temperature {
let value: Double

init?(value: Double) {
guard value >= -273.15 else {
return nil
}
self.value = value
}
}
enum Color : Int {
case Red = 0, Green = 1, Blue = 2

// implicitly synthesized
var rawValue: Int { /* returns raw value for current case */ }

// implicitly synthesized
init?(rawValue: Int) {
switch rawValue {
case 0: self = .Red
case 1: self = .Green
case 2: self = .Blue
default: return nil
}
}
}

--

--

Evangelist Apps specializes in developing iOS apps using latest Apple tools and technlogy. We help build apps to suit the customer’s needs and to take their business to the next level.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Savita Agrawal

I'm an iOS Developer and my passion is developing iOS, iPhone and tvOS apps. I'm proficient in C, C++, ObjC and Swift. I enjoy blogging, writting and reading.