I am trying to make a "Label Factory" that will help me to produce labels for a project.
I have a function
getLabel(of type: LabelTypeEnum,
_ labelTitle: String? = nil,
_ textColor: UIColor? = nil,
_ textAlignment: NSTextAlignment? = nil) -> Label
I then want to call it with any number of parameters, for example:
getLabel(of: .myLabel, .center)
which results in the error: " Type 'String?' has no member 'center' "
How do I tell the compiler that .center is not the labelTitle property?
I tried to specify the content by adding "alignment: .center" but it forces me to delete it.
If it's of any help I will ad the context of the code below.
static func getLabel(of type: LabelType,
_ labelTitle: String? = nil,
_ textColor: UIColor? = nil,
_ textAlignment: NSTextAlignment? = nil) -> Label {
switch type {
case .regular:
return RegularLabel(labelTitle, textColor, textAlignment)
case .title:
return TitleLabel(labelTitle, textColor, textAlignment)
case .description:
return DescriptionLabel(labelTitle, textColor, textAlignment)
case .header:
return HeaderLabel(labelTitle, textColor, textAlignment)
case .subHeader:
return SubHeaderLabel(labelTitle, textColor, textAlignment)
case .body:
return BodyLabel(labelTitle, textColor, textAlignment)
case .fatBody:
return FatBodyLabel(labelTitle, textColor, textAlignment)
case .smallGray:
return SmallGrayLabel(labelTitle, textColor, textAlignment)
}
}
Label init
convenience init(_ title: String? = nil, _ color: UIColor? = nil, _ alignment: NSTextAlignment? = nil) {
self.init(frame: .zero)
self.text = title ?? self.text
self.textColor = color ?? self.textColor
self.textAlignment = alignment ?? self.textAlignment
}
One of many calls
private lazy var titleLabel: UILabel = {
let label = LabelFactory.getLabel(of: .header, .center)
self.addSubview(label)
return label
}()
It's the curse of omitting the parameter labels because of convenience, this is supposed to work:
getLabel(of type: LabelTypeEnum,
labelTitle: String? = nil,
textColor: UIColor? = nil,
textAlignment: NSTextAlignment? = nil) -> Label
getLabel(of: .myLabel, textAlignment: .center)