gpt4 book ai didi

ios - 在 XCODE/Swift 中,如何创建一个可以从各种 View Controller 调用的函数?

转载 作者:IT王子 更新时间:2023-10-29 05:33:10 25 4
gpt4 key购买 nike

我想实现一组函数,并由我的应用中的各种 View Controller 调用它们。

最好的方法是什么?

一个在整个应用程序中使用的函数示例是这个函数,它将格式化的 Float 作为字符串返回:

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

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

}

最佳答案

我建议创建一个名为 Util.swift 的新文件,并将该函数粘贴到该文件中。这就是 Util.swift 的样子:

import UIKit

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

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

}

您可以在 Util.swift 中放置您需要的其他函数和常量。要在您的 View Controller 中调用它,您可以这样做:

var str = roundAndFormatFloat(float, numDecimalPlaces: decimalPlaces)

这是另一种选择。创建另一个名为 Util 的类,并将此函数作为类函数放入其中:

import UIKit

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

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

}
}

调用它看起来像这样:

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

您可以在这里添加您需要全局使用的其他类方法。请注意,您不能创建全局可用的变量或常量,因为类变量和常量尚未在 Swift 中实现。

关于ios - 在 XCODE/Swift 中,如何创建一个可以从各种 View Controller 调用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com