0

I have a Swift class that inherits from UIViewController, and I was wondering if there was any way that I could use the same class on a UITableViewController to avoid repetition.

class GradientViewController: UIViewController {
    // My class
}

Are there any ways to use this class on a UITableViewController, like so?

class MyTableViewController: GradientViewController {
    // My table view controller
}

Thanks in advance

AppleBetas
  • 88
  • 6

1 Answers1

0

Swift only supports single inheritance.

You could use a protocol to avoid repetition.

protocol YourProtocolName {
    // Protocol stuff
}

class GradientViewController: UIViewController, YourProtocolName {
    // Implement protocol requirements
}

class MyTableViewController: UITableViewController, YourProtocolName {
    // Implement protocol requirements
}

If it makes sense, you could even use a protocol extension to provide default implementations such that conforming types don't need to add any code to conform.

Matt Mathias
  • 932
  • 7
  • 7
  • Is there any way I could reference the UIView of the controller using this (self.view.addSubview), or override methods like viewWillTransitionToSize? – AppleBetas Mar 14 '16 at 21:03
  • Are you asking if you can do these things inside of the protocol extension? – Matt Mathias Mar 14 '16 at 21:13
  • I figured it out by adding a variable UIView to the protocol and using that in the extension's methods. I'm now getting an error that I'm not conforming to protocol. How do I make sure protocols use the default implementations I added in extensions? – AppleBetas Mar 14 '16 at 21:16
  • It's hard to help when I can't see what you're doing. Can you share the code? – Matt Mathias Mar 14 '16 at 21:22
  • I fixed that problem. Now I have a new one, that I cannot change the values of variables from my methods. I have posted the code here: http://pastebin.com/bsyQtscs. The problem can be found by looking for "Problem: I need to be able to change variables properties." Thanks for the help – AppleBetas Mar 14 '16 at 21:29
  • I think you need to mark `setGradient(_:)` as `mutating` in the protocol declaration, and again mark it as `mutating` in the protocol extension. – Matt Mathias Mar 14 '16 at 21:41
  • That worked great, thanks for that. Now I'm just having one more problem. When trying to use the mutating method, I get "Cannot use mutating member on immutable value: 'self' is immutable". Code: http://pastebin.com/RqgpeCUv – AppleBetas Mar 14 '16 at 22:25
  • I fixed it by declaring the protocol as class-only. Thanks for your help – AppleBetas Mar 14 '16 at 22:29
  • Ya. I was going to link to this: http://stackoverflow.com/questions/33098884/swift-2-error-using-mutating-function-in-protocol-extension-cannot-use-mutating – Matt Mathias Mar 14 '16 at 22:30