如何在Swift中创建静态类? [英] How can I create a static class in Swift?

查看:183
本文介绍了如何在Swift中创建静态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个称为VectorCalculator的静态类.也许应该将此函数放在我的Vector类中(类似于Obj-C中NSString的--stringByAppendingString方法)...如果您认为...请告诉我.

I'm looking to create a static class called VectorCalculator. Perhaps this function should just be placed in my Vector class (similar to NSString's --stringByAppendingString method in Obj-C)... and if you think that... let me know.

无论如何,我想向称为VectorCalculator的静态类中添加几个静态函数.它将计算点积"并返回一个Vector.另一个功能可能是计算并返回两个给定向量之间的角度".

Anyway I want to add a couple of static functions to a static class called VectorCalculator. It will calculate the 'dot product' and return a Vector. Another function will likely be to 'calculate and return the angle between two given vectors'.

A)有人会为此创建一个静态类吗?

A) Would anyone go this route of creating a static class for this or

B)我应该将这些函数添加为Vector类的实例函数,例如... public func dotProductWithVector(v: Vector) -> Vectorpublic func angleWithVector(v: Vector) -> Double.然后,这两个参数向量 v 都将应用于Vector类的主向量 u .

B) should I just add these functions as instance functions of the Vector class such as... public func dotProductWithVector(v: Vector) -> Vector and public func angleWithVector(v: Vector) -> Double. And then both of these argument vectors v will be applied to the Vector classes main Vector u.

使用A或B有什么好处?

What's the benefit of going either A or B?

如果您认为B,以供将来参考,您将如何创建在Swift中的全静态类?

If you think B, just for future reference, how would you create an all static class in Swift?

推荐答案

如果我对您的理解是正确的,那么您对情况A的Type方法感兴趣.您表示

If I've understood you correctly you are interested in Type methods in case A. You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method. (c)

    struct Vector {
        var x, y, z: Int
    }

    class VectorCalculator {
        static func dotProductOfVector(vec1: Vector, withVector vec2: Vector) -> Vector {
            let newX = //calc x coord;
            let newY = //calc y coord;;
            let newZ = ////calc z coord;;
            return Vector(x: newX,y: newY, z: newZ);
        }
    }

let vec1 = Vector(x:1, y:2, z:3)
let vec2 = Vector(x:4, y:5, z:6)
let v = VectorCalculator.dotProductOfVector(vec1, withVector: vec2)

关于B的好处,这取决于您要解决的任务.如果要保留原始向量不变,则使用A变体会更方便.但是我认为您可以同时提供两种类型的功能.

As for benefits of B it depends on tasks you solve. If you want to left original vectors unmodified it's more convenient to use A variant. But I think you could provide both types of functionality.

这篇关于如何在Swift中创建静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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