Search code examples
swiftinitializationinitinitializer

What's "init" used for in swift?


Is there difference ? And the effect of deinit ?

struct mark { var mark: Int }

struct mark { var mark: Int init(mark: Int) { self.mark = mark } }


Solution

  • init is used to set initial values for properties on a struct or class type at the time it is created, before any other methods may be called on it and before it is passed as a parameter to other functions or methods.

    In Swift, any non-optional properties must be set with initial values before init returns. Properties may be declared with initial values already, which excludes them from having to be set in an init method.

    • class types must have an init method implemented if there are any non-optional properties not already declared with initial values.

    • For struct types only, Swift will automatically generate an init method with parameters for each non-optional property that was not already declared with an initial value. You can optionally create any number of alternative init methods for the struct, as long as by the time each one returns, all non-optional properties have a value.

    • In your example, there is no difference between the init method created on the second line, and the automatically created init method provided for that struct type by Swift. But you could create alternate initializers that, for example, take a Double instead of an Int and then convert it internally before setting the mark property.

    I think the key point to realize is that even when you do not specify an init method yourself, one still exists, as created automatically by Swift for struct types. So in both line one and line two of your example, an init method is being called (and they are essentially identical implementations). The only difference is that you wrote the init implementation in the second line, and the Swift compiler writes the init method in the first line.

    deinitonly exists for class types, which are passed by reference and have memory management. Any deinit method you declare on a class you create will be called when there are no more references to that instance of the class and it will be released from memory. It's used to deregister from various observation patterns or otherwise clean up right before the instance is destroyed.