2

I didn't find any solution for that and there's a good chance that it's not possible but I'll give it a try (if it's not possible I'd be very happy to get a small explanation why).

I'm trying to create a class in Swift, let's call it Foo, and I want FooChild to inherit from Foo. So far, no problems. The thing is, I want Foo to dynamically inherit "any class", maybe by generic type.

Something like

class Foo<T> : <T>{

}

class FooChild : Foo<NSObject> {

}

class FooChild2 : Foo<UIview> {

}

I want both FooChild and FooChild2 inherit from Foo, but I want foo to inherit once from NSObject, and once from UIView (used random classes for the example).

Is that possible? Even in Objective-C code that I'll bridge somehow.

Brian
  • 14,610
  • 7
  • 35
  • 43
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44
  • Possible duplicate of [Limitation with classes derived from generic classes in swift](http://stackoverflow.com/questions/24138359/limitation-with-classes-derived-from-generic-classes-in-swift). – Martin R Jul 14 '15 at 11:42
  • possible duplicate of [Weird generics error](http://stackoverflow.com/questions/27920521/weird-generics-error) – nhgrif Jul 14 '15 at 12:26

1 Answers1

1

Swift 1.2

No, that is not possible.

What you can do is something like:

protocol Foo { }

class FooChild1: NSObject, Foo { }

class FooChild2: UIView, Foo { }

Swift 2

Yes, now this is possible.

Non-generic classes may inherit from generic classes. (15520519)

See: Xcode 7 Beta Release Notes, chapter "New in Swift 2.0 and Objective-C", section "Swift Language Features"

E.g. the following is possible:

import UIKit

class Foo<T> { }

class FooChild: Foo<NSObject> { }

class FooChild2: Foo<UIView> { }

let fooChild = FooChild()

let fooChild2 = FooChild2()

Also, in Swift 2 if you need protocol Foo from Swift 1.2 example to provide some default behaviour, you can use default protocol implementations.

You can use protocol extensions to provide a default implementation to any method or property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

See: The Swift Programming Language, Chapter "Protocols", Section "Providing Default Implementations"

0x416e746f6e
  • 9,872
  • 5
  • 40
  • 68
  • 1
    thanks, you know if i'll ask on FooChild "is Foo" it will return true? – Daniel Krom Jul 14 '15 at 11:40
  • 1
    Yes, it will return `true`. From the same chapter in the documentation (see the link in my answer): "You can use the `is` and `as` operators described in Type Casting to check for protocol conformance, and to cast to a specific protocol." – 0x416e746f6e Jul 14 '15 at 11:42