Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 378
user3535074 Avatar asked Oct 08 '14 19:10

user3535074


People also ask

How can I call viewDidLoad from another Viewcontroller?

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.


2 Answers

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.

like image 171
DrOverbuild Avatar answered Sep 24 '22 11:09

DrOverbuild


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"
    }

}
like image 20
Ovi Bortas Avatar answered Sep 23 '22 11:09

Ovi Bortas