0
protocol CodableWithDefault: Codable {
    static var `default`: Self { get }
}

extension Set: CodableWithDefault {
    static var `default`: Set {
        return Set()
    }
}

This was working fine in Swift 4, but since 4.1 it complains:

'CodableWithDefault' requires that 'Element' conform to 'Encodable'

I could not find any way to express that I want to have an extension of Set that is constrained to Element also implement Encodable.

Is this at all possible with Swift 4.1?

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
plu
  • 1,321
  • 10
  • 14

2 Answers2

5

With this

extension Set: CodableWithDefault { ... }

you are making Set conform to Codable without providing the required methods.

In Swift 4.1 you can avoid the implementation of the required methods only if the generic element of Set is Codable.

So you need to restrict your extension

extension Set: CodableWithDefault where Element : Codable {
    static var `default`: Set {
        return Set()
    }
}
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
1

You need to make Element Codable.To use your extension, you would need to do

let set = Set<Yourtype>.defaults

Note that there is Yourtype. That is what the compiler means by Element. Now if you use this code:

extension Set: CodableWithDefault where Element: Codable {
    static var defaults: Set {
        return Set()
    }
}

the code will compile because Element is Encodable and Decodable.

Papershine
  • 4,995
  • 2
  • 24
  • 48