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
}
You have to call _ = metronomePlay. view , which will lazily load the view of SecondVC and subsequently execute viewDidLoad , before actually calling metronomePlay. metronome . Save this 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.
The Swift way is to extend UIViewController
and add your functions there.
Swift 3 Example:
extension UIViewController {
func roundAndFormatFloat(floatToReturn : Float, numDecimalPlaces: Int) -> String{
let formattedNumber = String(format: "%.\(numDecimalPlaces)f", floatToReturn)
return formattedNumber
}
func foo() -> String {
return "foo"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With