user6451264
user6451264

Reputation:

How can I avoid repeating these type constraints?

A have a lot of functions with the following signature:

func defilter_up<ReferenceLine:Collection>(line:ReferenceLine) where ReferenceLine.Iterator.Element == UInt8, ReferenceLine.Index == Int

func defilter_average<ReferenceLine:Collection>(line:ReferenceLine) where ReferenceLine.Iterator.Element == UInt8, ReferenceLine.Index == Int

func defilter_sub<ReferenceLine:Collection>(line:ReferenceLine) where ReferenceLine.Iterator.Element == UInt8, ReferenceLine.Index == Int

etc.

These type constraints are getting very long and unwieldy. Is there a good way I can avoid repeating typing them out, something equivalent to a typealias for generics?

Upvotes: 1

Views: 73

Answers (1)

Connor Neville
Connor Neville

Reputation: 7361

You can make the containing class/struct generic:

struct MyClass<ReferenceLine:Collection where 
    ReferenceLine.Iterator.Element == UInt8, 
    ReferenceLine.Index == Int> {

    func defilterUp(line: ReferenceLine) { ... }
    func defilterAverage(line: ReferenceLine) { ... }
    func defilterSub(line: ReferenceLine) { ... }
}

Another option is to refactor the code such that they are functions of the genericized object, like below. This is a substantial change in the structure of your code, so without context I can't say for sure this will work for your use case.

extension Collection where Iterator.Element == UInt8, Index == Int {
    func defilterUp() { ... }
    func defilterAverage() { ... }
    func defilterSub() { ... }
}

If these functions are meant to be private to a single class, you can mimic the access control by making this a private extension and put it in the same file as the using class.

Upvotes: 1

Related Questions