Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"subclassing" generic structs

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.

like image 389
Edward Ashak Avatar asked Jul 16 '15 21:07

Edward Ashak


1 Answers

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.

like image 54
Duncan C Avatar answered Oct 18 '22 19:10

Duncan C