"subclassing" generic structs
Asked Answered
S

2

6

Is it possible to subclass a generic struct in swift ?

assume we have a struct:

struct Foo<T> {}

and I wana "subclass" it to add some functionality:

struct Something {}
struct Bar<F>: Foo<Something> { /*<<<= ERROR: Inheritance from non-protocol type 'Foo<Something>' */
    let store: Something
    let someF: F
}

If you replace struct with class this example works.

class Foo<T> {}
//struct Bar1<T>: Foo<T> { /* Inheritance from non-protocol type 'Foo<T>' */
//    let name = "Bar"
//}


class Something {}
class Bar<F>: Foo<Something> { /* Inheritance from non-protocol type 'Foo<Something>' */
    let store: F?
    init(value: F?) {
        self.store = value
    }
}

Any idea how to make this work for structs ?

I'm trying to stick to value types but swift is making it hard.

Stillwell answered 16/7, 2015 at 21:49 Comment(0)
C
13

It's my understanding that inheritance is a central difference between classes and non-class objects like structs and enums in swift. Classes have inheritance, other objects types do not.

Thus I think the answer is "No, not now, and not ever, by design."

EDIT:

As pointed out by Ammo in his comment below, another crucial difference is the fact that class objects are passed by reference while non-class objects like structs are passed by value.

Checkroom answered 16/7, 2015 at 22:33 Comment(1)
it is ONE of the big differences. However, the behavior of struct instances being passed by value (i.e. copied) versus class instances being passed by reference and reference counted is at least as important a differenceAlansen
E
-2

Since inheritance is not possible for value types like struct, I would build it like this:

struct Foo<T> { //... }

struct Bar<T> {
  let store: Something
  let someT: T
}

Then use composition to build something out of them:

struct FooBar {
  let foo: Foo<SomethingFoo>
  let bar: Bar<SomethingBar>
}
Equimolecular answered 22/1 at 0:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.