How to properly create initializers in Swift?

designated initializer swift
swift static initializer
swift failable initializer
swift override convenience init
let property may not be initialized directly use self init or self instead
swift class constructor with parameters
swift override init
swift class has no initializers

I have a class NewFormView: UIView inside of which I have

var viewModel: NewFormViewModel

where NewFormViewModel has initializer:

var user: Users
init(for user: Users) {
    self.user = user
}

So I want: When I initialize my NewFormView to pass it the user: Users and initialize my viewModel with it. Like:

let newFormView = NewProfileFormView(user: user)

but when I'm trying to create initializers for NewProfileView:

init(user: Users) {
    super.init(user: user)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

I get error Argument labels '(user:)' do not match any available overloads. I've tried also with convenience init but got another error. I think my problem is in thinking wrong. Could you please explain me how can I solve it and can call:

let newFormView = NewProfileFormView(user: user)

You'll need to create another init where you pass both user and the frame, for example

    class Form: UIView {
    private var model: FormModel!
    private var user: User!

     init(user: User, frame: CGRect) {
        self.user = user
        self.model = FormModel.init(user: user)
        super.init(frame: frame) //<-- since your view is derived from UIView, you need to set your base init 
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}

Initializer in Swift, In swift, we need to understand it deeply and in a proper manner before The default initializer simply creates a new instance with all of its  When the custom initializers are not provided by the user, Structure types in Swift 4 will automatically receive the 'memberwise initializer'. Its main function is to initialize the new structure instances with the default memberwise initialize and then the new instance properties are passed to the memberwise initialize by name.

If you are using .Xib file for your view, you can init UIView like this:

var user: Users?

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

override init(frame: CGRect, user: Users) {
    super.init(frame: frame)
    commonInit()
    self.user = user
}

private func commonInit() {
    Bundle.main.loadNibNamed("yourXibName", owner: self, options: nil)
    addSubview(contentView)
    contentView.frame = self.bounds
    contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}

that contentView is a @IBOutlet of the main view in your class.

How to properly create initializers in Swift?, You'll need to create another init where you pass both user and the frame, for example class Form: UIView { private var model: FormModel! Home » Blog » App Development » Initializers & init() Explained In Swift. Initializers & init() Explained In Swift Written by Reinder de Vries on March 24 2020 in App Development. In Swift, an initializer is a special init function that we use to create objects of a particular class, struct or type. They’re used to “construct” an

 struct Users {
     var placeholder: String?
 }

 class NewFormView: UIView {
     var viewModel: NewFormViewModel

     init(user: Users, frame: CGRect) {
         self.viewModel = NewFormViewModel(for: user)
         super.init(frame: frame)
     }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
 }

 class NewFormViewModel {
     var user: Users

     init (for user: Users) {
         self.user = user
     }
 }

Example Usage:

let formView = NewFormView.init(user: Users.init(placeholder: ""), frame: CGRect())

Where user follows your proper initializers for your Users struct/class and you give the frame the proper dimensions you expect the view to be.

Initializers in Swift, What characteristics should an initializer ideally have, and what sort of how their memberwise initializers enable us to easily create a new instance of How do you like your initializers to work, and what kind of principles do  Right-click the InitializerDemo group and then select New File from the popup menu. On the left side of the Create File dialog under the iOS section, select Source. On the right side of the dialog, select the Swift File template, and then click Next.

The problem is how you're calling

super.init(user: user)

Your NewFormViewModel initializer has the signature init(for:) therefore you should change your code like this:

super.init(for: user)

Using Custom Initializers in Swift, Custom initializers have always been a staple of Cocoa. but intelligently and safely handles initialization with a 4-step safety check To create a new Person object we just need to call the appropriate designated initializer: Swift has a very clear, specific sequence of operations that are done in initializers. Let’s start with some basic examples are work our way up to a general case. Let’s take an object A.

Swift init(), Swift init, Swift convenience init, swift initializers, swift static init, swift optional init, swift Initialization is what happens when we create an instance of some type. too thereby adding responsibilities to properly inherit and initialize all values. Swift provides a default initializer for any structure or class that provides default values for all of its properties and does not provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values.

Swift init patterns, Now, the rule above says that we have to init all the properties, so let's make that by creating our very first init method. struct Point { let x: Int let y:  Multiple Initializers in a single class (swift) Create a Triangle class with properties to store the length of each side. Triangles are called scalene when all three sides are of different lengths, isosceles when two sides have the same length, or equilateral when all three sides have the same length.

Adding Swift Convenience Initializers, Do you ever find yourself wishing that Apple included an extra initializer to a UIKit class? Swift extensions make it easy to add new initializers to  Sometimes, we may want to initialize a class, but the initialization process. 0:12. depends on external data that may or may not be available. 0:16. To deal with this we have two kinds of specialize init methods. 0:19. The first of which is a failable initializer. 0:23. When initializing an object using a failable initializer, the result. 0:27

Comments
  • Hint: Initializers of a subclass of UIView must call one of the provided initializers of UIView. UIView does not have an init(user: Users) initializer.
  • @rmaddy yes, I know. Thats why I tried it with convenience init where in the main init I tried to initialize with frame: frame and in convenience like convenience init(frame: CGRect, user: Users) but I got several errors again =/
  • May I suggest a thorough (re-)reading of the Initialization chapter in the Swift book. It covers all of the little details you need to deal with when creating and initializing subclasses.
  • @rmaddy I'm still confusing. Maybe you could help me?
  • Update your question with more specific details about how you are still confused. And what's wrong with some of the answers you've received below?
  • You don't necessarily need to add the frame parameter. The init(user:) can pass some hardcoded frame if appropriate.
  • I tried that also. In this case I get Property 'self.viewModel' not initialized at super.init call
  • in your declaration try var viewModel: NewFormViewModel! @J.Doe
  • (sorry I didn't mean to add the second code, I've updated it) the reason you are having the first issue is because you'd need to initialize it within your coder init too @J.Doe