Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make struct init() parameter accept two types?

I believe this would be generics but I am unsure of how to implement it. I have a simple struct for defining a button on my app. I want to be able to either pass directly in an Image() or compose an image with Image(systemName: String) if a user passes in a String.

import SwiftUI

public struct TextFieldStepperButton {
    let image: Image
    let color: Color
   
    // image: Image should accept both (String && Image)
    public init(image: Image, color: Color = Color.accentColor) {
        // Detect if image == String || Image then define it depending on result
        self.image = image
        self.color = color
    }
}

Is there a way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This isn’t a problem of generics; you just need two inits.

public init(image: Image, color: Color = Color.accentColor) {
    self.image = image
    self.color = color
}

// And then add a convenience that calls the other:

public init(imageNamed: String, color: Color = Color.accentColor) {
    self.init(image: Image(systemName: imageNamed), color: color)
}

I would recommend having different parameter names (image vs imageNamed), but you could unify them and use image for both if you like.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading