假设我有一个名为 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/