0

I’m writing a protocol called JSONDataInitializable, which will enable values to be initialized from Data that contains JSON using JSONDecoder.

Since it’s not possible to explicitly use generics within initializers, I declared a universal, type-agnostic helper method in a protocol extension, which the initializer later calls.

However, I came up with not one, but two ways to write such a method.

(1):

private static func initialize<T: JSONDataInitializable>(from jsonData: Data) throws -> T {
    return try JSONDecoder().decode(T.self, from: jsonData)
}

(2):

private static func initialize(from jsonData: Data) throws -> Self {
    return try JSONDecoder().decode(Self.self, from: jsonData)
}

Could you explain the difference between these methods? They both seem to produce the same result.

The only visible difference is the protocol conformance part in the first variant. However, the methods are declared in a protocol extension and therefore only available to types which conform to the protocol.

UPD

Here’s the complete protocol declaration:

protocol JSONDataInitializable: Decodable {
    init?(from jsonData: Data)
}

extension JSONDataInitializable {

    init?(from jsonData: Data) {
        do {
            self = try Self.initialize(from: jsonData)
        } catch {
            print(error)
            return nil
        }
    }

    // (1)
    private static func initialize<T: JSONDataInitializable>(from jsonData: Data) throws -> T {
        return try JSONDecoder().decode(T.self, from: jsonData)
    }

    // ⬆⬆⬆
    // OR
    // ⬇⬇⬇

    // (2)
    private static func initialize(from jsonData: Data) throws -> Self {
        return try JSONDecoder().decode(Self.self, from: jsonData)
    }

}

Let’s say we have a struct called User that’s Decodable. We need to initialize values of User from JSON (stored as Data). With the protocol, initialization works like that:

// Protocol conformance declaration
extension User: JSONDataInitializable { }

// JSON stored as Data
let networkData = ...

// Initialization
let john = User(from: networkData)
2
  • You shouldn't need a custom protocol in your first method, simply restrict T to Decodable. Also, it would help if you included a minimal reproducible example, especially showing where (in what scope) these methods are declared. Mar 29, 2019 at 10:36
  • @DávidPásztor Thanks for your comment. I added the full protocol declaration. Mar 29, 2019 at 13:44

1 Answer 1

1

Your second implementation, using Self is the one that matches your requirements. You want to create an initializer in a protocol, which you can call on the type you want to initialize. Self in protocol functions refers to the type that you call the specific method on.

On the other hand, the generic implementation would allow you to initialize any types conforming to the protocol, but in your init(from:) method you assign the return value to self, so the generic type parameter T will be inferred as Self. This makes it unnecessary to make the method generic, since on a specific type, T will always be Self.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.