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?
CodePudding user response:
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.