Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How inherit the struct in swift?

Is there any to inherit a struct in Swift?

struct Resolution {
    var width = 0
    var height = 0
}
struct Display : Resolution {}
like image 502
Ravish Kumar Avatar asked Oct 25 '25 14:10

Ravish Kumar


1 Answers

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
like image 139
JeremyP Avatar answered Oct 27 '25 02:10

JeremyP