Skip to content
  • Home
  • About us
  • Contact
  • Privacy Policy
  • Disclaimer
  • Swift Online Compiler
iOS Interview Questions and Tutorials

iOS Interview Questions and Tutorials

Failable initializers in Swift

Posted on November 26, 2023November 26, 2023 By Sid No Comments on Failable initializers in Swift
Failable initializers in Swift
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.

Blog Tags:Failable initializers in Swift

Post navigation

Previous Post: Mutating keyword in Swift
Next Post: Convenience initializers in Swift

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Asked iOS Interview Questions

  • Top iOS Interview Questions and Answers

Categories

  • Associated Types(7)
  • Blog
  • Dictionary in Swift(20)
  • Initializers
  • Property Wrapper
  • Singleton in Swift
  • User Defaults(4)
  • XCode 15 Errors

Recent Comments

  1. Sid on Cycle inside MyApp; building could produce unreliable results
  2. Anominous on Cycle inside MyApp; building could produce unreliable results
  3. Aisha on @objc Attribute in Swift

Recent Posts

  • Enums in Swift: Brief Explanation with Code Examples
  • Higher-Order Functions in Swift: Brief Explanation with Code Examples
  • Mutability in Structs and Classes in Swift
  • Delegate Pattern in Swift
  • resueIdentifier in Swift

DSA in Swift

  • 2D Array in Swift: Interview Questions

Copyright © 2025 iOS Interview Questions and Tutorials.

Powered by PressBook WordPress theme