Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is init() relevant in Swift protocol?

Protocols in Swift can declare the init() method in their definition. However, I can't think of any use case where this solves any problem other than forcing the conforming classes to define the init() as in the protocol. We can call the declared methods on the protocol type but init on protocol cannot be used to instantiate its object, which is its only purpose.

What problem does declaring init() method in a protocol solve?

like image 986
Shubham Avatar asked Mar 09 '17 11:03

Shubham


People also ask

Why do we use init in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.

How many types of init are there in Swift?

Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.

Can we use init in protocol Swift?

Swift allows programmers to directly initialize protocols by conforming to its types. We can declare the initializers as a part of protocol the same as a normal initializer, but we won't use the curly braces or an initializer body.

CAN protocol init?

Protocols can require specific initializers to be implemented by conforming types. You write these initializers as part of the protocol's definition in exactly the same way as for normal initializers, but without curly braces or an initializer body: protocol SomeProtocol { init(someParameter: Int)


1 Answers

I think the real utility comes when it's used as a constraint in a generic class o function. This is real code from one of my projects.

I declare a protocol with a init:

protocol JSONCreatable {
    init(fromJson json: JSON)
}

Then, in a generic function where I return a class that conforms to that protocol:

import SwiftyJSON

extension JSON {
    func asObject<T>() -> T? where T: JSONCreatable {
        if isEmpty {
            return nil
        }
        return T(fromJson: self)
    }

    func asArray<T>() -> [T] where T: JSONCreatable {
        return array?.map{ json in T(fromJson: json) } ?? []
    }
}

This allows me to do things like this:

let user: User = json["user"].asObject()
let results: [Element] = json["elements"].asArray()
like image 80
redent84 Avatar answered Oct 09 '22 00:10

redent84