Search code examples
swift3xcode8

Move function from ViewController to swift file so it's reusable


I have a function to change the label text color on several labels that are part of an outlet collection.

I want to move this function from the view controller to a project file so I can reuse it.

How do I replace the reference to self and pass the proper view conroller and outlet collection to the function?

func setLabelColor() {

    var counter = 0
    let myColor = UIColor.white
    while counter < labelOutletCollection.count {

        self.labelOutletCollection[counter].textColor = myColor

        counter += 1
    }
}

Solution

  • You may move this code to a separate file where you store your globally usable functions and make the array of labels a parameter.

    func setLabelColor(_ labels: [UILabel]) {
        var counter = 0
        let myColor = UIColor.white
    
        while counter < labels.count {
            labels[counter].textColor = myColor
    
            counter += 1
        }
    }
    

    On another node, this code can be much cleaner by replacing it with a single forEach statement:

    labels.forEach { $0.textColor = .white }
    

    You can use this function like this:

    setLabelColor(labelOutletCollection)