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

3 Solutions Collect From Internet About “In XCODE / Swift, how can I create a single function which can be called from various view controllers?”

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

}

Creating Util class in Swift:

  1. Create new file with name Util
  2. Create a class functions : class func funtionname:() -> {}

Exmaple:

import UIKit
import Foundation

    class Util: NSObject {


        //MARK: - SET USER LOGGED IN
        class func set_IsUserLoggedIn(state : Bool) {
            var userloggedin:     UserDefaults?
            userloggedin        = UserDefaults.standard
            userloggedin?.set(state, forKey: "IS_USER_LOGGED_IN")
        }


        //MARK: - GET USER LOGGED IN
        class func get_IsUserLoggedIn() -> Bool {

            var userloggedin:     UserDefaults?
            userloggedin        = UserDefaults.standard

            var checkUser:Bool? = false
            checkUser           = userloggedin?.bool(forKey: "IS_USER_LOGGED_IN")

            return checkUser!
        }



    }

You can call the Util function in Any Class file
like:

 if Util.get_IsUserLoggedIn(){
        print("User is logged in")

    }
    else{
        print("User is not logged in")
    }