Home > Enterprise >  Simple method that creates and manage constants
Simple method that creates and manage constants

Time:05-03

Usually I first declare constants and then set their settings using some method. But is it safe to write a simple method that declare constants and variables?

For example, I create such method - that works fine up to now:

func textSettings(labelName: String, text: String, color: UIColor, fontSize: Int, xPosition: CGFloat, yPosition: CGFloat) {
               
               let labelName = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 21))
               labelName.textAlignment = .center
               labelName.text = text
               labelName.textColor = color
               labelName.font = labelName.font.withSize(CGFloat(fontSize))
               labelName.sizeToFit()
               labelName.layer.position.x = xPosition
               labelName.layer.position.y = yPosition
               UIScrollView.addSubview(labelName)
               
           }

But is it safe to use it? Does such process of creating objects has serious drawbacks?

CodePudding user response:

This is absolutely possible, as soon as you note this :

  • The only reference to your newly created label is kept by the scrollView.
  • Maybe a more significant name like addSettingsLabel would be clearer.
  • Maybe splitting creation and use is suitable, like :
createSettingsLabel(labelName: String, text: String, color: UIColor, fontSize: Int, xPosition: CGFloat, yPosition: CGFloat) -> UILabel
{
...
}


let settingsLabel = createSettingsLabel(...)
scrollView.addSubview(settingsLabel)

  • Related