Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a static class in Swift?

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.

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) Would anyone go this route of creating a static class for this or

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.

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

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

like image 466
chris P Avatar asked Jan 25 '16 12:01

chris P


People also ask

How do you make a class static in Swift?

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 { ... } }

How do you create a static class?

We can declare a class static by using the static keyword. A class can be declared static only if it is a nested class. It does not require any reference of the outer class. The property of the static class is that it does not allows us to access the non-static members of the outer class.

What is static class in IOS?

if you want to create static property means, you are creating a class variable. properties are only used for instance variable. If you creating a static means all objects share the same variable; Because it is class variable. you can declare it in the implementation file of your class.

What is static in IOS Swift?

The Static keyword makes it easier to utilize an objects properties or methods without the need of managing instances. Use of the Static keyword in the Singleton pattern can reduce memory leaks by mismanaging instances of classes.


1 Answers

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 {
        ...
    }
}
like image 151
Cœur Avatar answered Oct 04 '22 16:10

Cœur