user3535074 user3535074 - 1 month ago 9
iOS Question

In XCODE / Swift, how can I create a single function which can be called from various view controllers?

I would like to implement a set of functions and that they be called by various view controllers in my app.

Whats the best approach for this?

An example of a function to be used throughout the app is this one which returns a formatted Float as a string:

func roundAndFormatFloat(floatToReturn : Float, numDecimalPlaces: Int) -> String{

let formattedNumber = String(format: "%.\(numDecimalPlaces)f", floatToReturn)
return formattedNumber

}

Answer

I suggest creating a new file called Util.swift, and paste that function into that file. This is what Util.swift would look like:

import UIKit

func roundAndFormatFloat(floatToReturn : Float, numDecimalPlaces: Int) -> String{

    let formattedNumber = String(format: "%.\(numDecimalPlaces)f", floatToReturn)
    return formattedNumber

}

You can place other functions and constants you need in Util.swift. To call it in your view controller, you do this:

var str = roundAndFormatFloat(float, numDecimalPlaces: decimalPlaces)

Here is another option. Create another class called Util, and put this function in there as a class function:

import UIKit

class Util{
    class func roundAndFormatFloat(floatToReturn : Float, numDecimalPlaces: Int) -> String{

        let formattedNumber = String(format: "%.\(numDecimalPlaces)f", floatToReturn)
        return formattedNumber

    }
}

Calling it would look like this:

var str = Util.roundAndFormatFloat(float, numDecimalPlaces: decimalPlaces)

You can add other class methods here that you need to use globally. Note that you cannot create globally available variables or constants this, as class variables and constants have not been implemented yet in Swift.