How can I create a static class in Swift?

匆匆过客 提交于 2019-11-30 17:42:20

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)

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.

how would you create an all static class in Swift?

static means no instance, so I would make it a struct with no initializer:

struct VectorCalculator {
    @available(*, unavailable) private init() {}

    static func dotProduct(v: Vector, w: Vector) -> Vector {
        ...
    }
}
Sprotte

I think what you looking for are class functions? Maybe your Answer can be found here. How do I declare a class level function in Swift?

class Foo {
    class func Bar() -> String {
       return "Bar"
    }
}

Foo.Bar()

In Swift 2.0 you can use the static keyword instead of class. But you should use static keyword for structs and class keyword for classes

//Edit just saw that i properly misunderstood your question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!