Klaas Klaas - 1 year ago 65
Swift Question

How can I create a generic class that is constrainted to structs?

As the Swift Language Guide points out generic types can be constraint to classes or protocols like this:

public class MyGenericClass<T:Equatable> {
func printEquality(a:T, b:T) {
if a == b {
} else {
print("not equal")

Can I somehow restrict
to be a

My use case is an observer class for value types that should only be used by structs.

As a side note: I know that there are e.g. class-only protocols, that are only implementable by classes. This is not really related, but shows that there is sometimes a special way to reach a goal.

protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol {
// class-only protocol definition goes here

Answer Source

You can't (as of Swift 2.2).

It's simply not possible. There's no struct version of AnyObject, i.e. an AnyValue protocol (automatically implemented for all value types).

I've faced this exact problem myself, and I'm sorry to say that there's no solution other than to strictly abide by an informal protocol. Here's to hoping Swift 3 solves this.