ios - 在 Swift 的另一个类中使用一个类中的函数

标签 ios swift

假设我有一个名为 Math 的类(class)

class Math{

    func add(numberOne: Int, numberTwo: Int) -> Int{

        var answer: Int = numberOne + numberTwo
        return answer
    }

在这个类中有一个函数允许用户将两个数字相加。

我现在有另一个类,它是 UIViewController 的子类,我想使用 Math 类中的 add 函数,我该怎么做?

class myViewController: UIViewController{

    //Math.add()???

}

最佳答案

如果您希望能够说Math.add(...),您将需要使用类方法 - 只需添加func 之前:

class Math{

    class func add(numberOne: Int, numberTwo: Int) -> Int{

        var answer: Int = numberOne + numberTwo
        return answer
    }
}

然后你可以像这样从另一个 Swift 类中调用它:

Math.add(40, numberTwo: 2)

将其分配给变量i:

let i = Math.add(40, numberTwo: 2) // -> 42

关于ios - 在 Swift 的另一个类中使用一个类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24921622/

相关文章:

ios - 使用 CoreNFC 检测 ISO/IEC 14443(Mifare Ultralight 或 Classic)NFC 卡

ios - Xcode ipa 在 iOS 5.1 上安装,但在 iOS 5.1.1 上失败

ios - 从 TabBar View Controller 中移除 UIElement

swift - 在 Swift 2 中设置多个类属性时的守卫

ios - 我应该在 iOS 应用程序中的什么位置存储默认字符串列表?

oop - 为什么协议(protocol)的关联类型在 Swift 中不使用泛型类型语法?

ios - 在没有 API 的情况下以 swift 显示网页内容

ios - 如何使用 UITableViews 通过 Swift 创建静态和动态行

swift - UIAlertAction 在存档并导出为临时文件后不执行操作

swift - 从多个 UICollectionVIews 内部的 UICollectionViewCell 推送一个新的 UICollectionViewController