Is there any to inherit a struct in Swift?
struct Resolution {
var width = 0
var height = 0
}
struct Display : Resolution {}
structs can only inherit (if that is the right word) from protocols. The cannot inherit from a base struct so you cannot do
struct Resolution {
var width = 0
var height = 0
}
struct MyStruct: Resolution { ... } // ERROR!
So you have two options. The first is to use a class instead. The second is to refactor your code to use protocols.
So, if you have some common methods, you might do:
protocol PixelContainer
{
var width: Int { get }
var height: Int { get }
}
extension PixelContainer
{
var count: Int { return width * height }
}
struct Resolution: PixelContainer
{
var width = 10
var height = 20
}
let numPixels = Resolution().count // Legal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With