使用Swift中另一个类中的一个类的函数 [英] Use function from one class in another class in Swift

查看:401
本文介绍了使用Swift中另一个类中的一个类的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想说我有一个名为Math的类

So lets say I have a class called Math

class Math{

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

        var answer: Int = numberOne + numberTwo
        return answer
    }

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

In this class there is a function which allows the user to add two numbers.

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

I now have another class which is a subclass of a UIViewController and I want to use the add function from the Math class, how do I do this?

class myViewController: UIViewController{

    //Math.add()???

}


推荐答案

如果你希望能够说 Math.add(...),你想要使用类方法 - 只需添加<$ c在 func 之前$ c> class :

If you want to be able to say Math.add(...), you'll want to use a class method - just add class before func:

class Math{

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

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

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

Then you can call it from another Swift class like this:

Math.add(40, numberTwo: 2)

将其分配给变量

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

这篇关于使用Swift中另一个类中的一个类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆