Method specialization for type | Segmentation fault

Hello,

I've been trying to provide different implementation for selected types conforming to a protocol inside a generic class and so far I have failed. I've tried so hard, I've made my compiler crash (Segmentation fault 11, snipper following).

I've tried other approaches. Would you consider approach like "cpp template specialization" as something not achievable in Swift today, or is there some primitive solution I have missed?

Only thing I haven't tried yet it a huge switch-case with case for each and every type I want to specialize.

import Foundation

enum AnError: Error { case anError }

class Wrapper<T>: Coding where T: Codable {

    let encoder: PropertyListEncoder = {
        let newEncoder = PropertyListEncoder()
        newEncoder.outputFormat = .binary
        return newEncoder
    }()

    let decoder: PropertyListDecoder = PropertyListDecoder()

    var typeRepre: T?
    var dataRepre: Data {
        get {
            do {
                return try encode() ?? Data()
            } catch {
                print("Error encoding \(typeRepre) into keychain with \(error)")
                return Data()
            }
        }
        set {
            do {
                try decode(from: newValue)
            } catch {
                print("Error decoding \(newValue) from keychain with \(error)")
                typeRepre = nil
            }
        }
    }
}

protocol Coding: AnyObject {
    associatedtype Value: Codable

    var encoder: PropertyListEncoder { get }
    var decoder: PropertyListDecoder { get }

    var typeRepre: Value? { get set }

    func encode() throws -> Data?
    func decode(from data: Data) throws
}


extension Coding where Value == String {
    func encode() throws -> Data? {
        guard let value = typeRepre else {
            return nil
        }
        guard let data = value.data(using: .utf8) else {
            throw AnError.anError
        }
        return data
    }

    func decode(from data: Data) throws {
        guard let string = String(data: data, encoding: .utf8)
                        ?? String(data:data, encoding: .ascii) else {
            throw AnError.anError
        }

        typeRepre = string
    }
}

extension Coding where Value: Codable {
    func encode() throws -> Data? {
        return try typeRepre.flatMap(encoder.encode(_:))
    }

    func decode(from data: Data) throws {
        typeRepre = try decoder.decode(Value.self, from: data)
    }
}


Please file a bug report at bugs.swift.org if the compiler is crashing (which it never should)!

Terms of Service

Privacy Policy

Cookie Policy