Swift Framework Does Not Include Symbols from Extensions to Generic Structs

Swift Framework does not include symbols from extensions to generic structs

I posted on the Apple Developer forums and an Apple employee responded that this is a known bug.

It looks like the compiler gets the mangled symbol names of methods in generic extensions wrong when they live in a different framework.

Generic function with structs

As mentioned in other answers using a protocol with date property makes most sense in your case. However theoretically you could also use keypaths to achieve that. You could make a function that takes any instances and gets dates from them in a similar way as below:

func printDates(data: [Any], keyPath:AnyKeyPath)  {
for value in data {
if let date = value[keyPath: keyPath] as? Date {
print("date = \(date)")
}
}
}

and then pass for example your BodyWeightCalendarModel instances as below:

let one = BodyWeightCalendarModel(date: Date(), weight: 1)
let two = BodyWeightCalendarModel(date: Date(), weight: 2)
printDates(data: [one, two], keyPath: \BodyWeightCalendarModel.date)

But still a protocol makes more sense in your case.

Protocol extensions on Structs causes compile error 'Self' constrained to non-protocol type

This is an expected behaviour considering struct are not meant to be inherited which : notation stands for.

The correct way to achieve what you described would be something like equality sign like:

extension MyProtocol where Self == Foo {
func bar() {
print(myVar)
}
}

But this doesn't compile for some stupid reason like:

Same-type requirement makes generic parameter Self non-generic

For what it's worth, you can achieve the same result with the following:

protocol FooProtocol {
var myVar: String { get }
}
struct Foo: FooProtocol, MyProtocol {
let myVar: String
}

protocol MyProtocol {}
extension MyProtocol where Self: FooProtocol {
func bar() {
print(myVar)
}
}

where FooProtocol is fake protocol which only Foo should extend.

Many third-party libraries that try to extend standard library's struct types (eg. Optional) makes use of workaround like the above.



Related Topics



Leave a reply



Submit