poPaTheGuru
poPaTheGuru

Reputation: 1100

Use Struct as a parameter in a function in Swift

I have the next scenario :

I have created a Swift package that I am using in a main application. In this Swift Package I want to use some colors because it's an UI package. My struct Colors is already defined in my main application and I don't want to define it again in the package so I am trying to send my struct Colors to the package.

Also my struct Colors have another struct General in it like:

struct Colors {
     struct General {
          static let mainColor = "5F8E3F".toColor
     }
}

This is how I call it in my package:

func setupContent(withMainStruct mainStruct: Colors) {
    print(mainStruct.General.mainColor)
}

This is how I send it from main application:

let mainStruct = ColorStruct()
cell.setupContent(withMainStruct: mainStruct)

My main problem is:

Static member 'General' cannot be used on instance of type 'Colors'

Is there any way to do this?

All I want is to use the values of the struct, I don't need to update any of it.

Upvotes: 1

Views: 879

Answers (1)

Drobs
Drobs

Reputation: 770

Sounds like you want to define a protocol in your Package which is fulfilled by a struct in your App. So you can just provide these predefined values to the package.

So something like this.

In the App:

struct AppColors: Colors {
    let general: GeneralColors = General()

    struct General: GeneralColors {
        let mainColor = UIColor.blue
     }
}

configLib(colors: AppColors())

In the Package

protocol Colors {
    var general: GeneralColors { get }
}

protocol GeneralColors {
    var mainColor: UIColor { get }
}

func configLib(colors: Colors) {
    print(colors.general.mainColor)
}

Upvotes: 2

Related Questions