How can I create a static class in Swift?
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.
Are static classes supported by Swift?
No, Swift has no concept of a static class. But if you have no assignable property anyway, what difference will initialization make? I can think of 2 options:
Mark the class as
final
so it cannot be inherited:final class MyClass { .... }
Use a
struct
, which has no inheritance:struct MyUtilities { ... }
How do you make a static class in swift?
There's no static class, but you can make one by just adding static methods only.
The problem is that (as of today) classes cannot have static properties, so you have 2 options:
- use a struct instead of a class, defining all its methods and properties as static
- use the singleton pattern
The second option is in my opinion a better solution, unless you have specific reason for not wanting it.
How does one create a 'static' in a Swift class extension?
You can add static members to class extensions just the same as on classes. You need to prefix the class name to the static member name when you use it, e.g. NSDate.dateFormatterUTC
, even if you’re using it in the same class.
This works:
extension NSDate {
private static let dateFormatterUTC: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
return formatter
}()
public var UTC : String {
return NSDate.dateFormatterUTC.stringFromDate(self)
}
}
It’s also not the worst thing in the world just to use a private constant:
private let dateFormatterUTC: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
return formatter
}()
extension NSDate {
public var UTC : String {
return dateFormatterUTC.stringFromDate(self)
}
}
This is not significantly worse than the static class member, because Swift’s private
is file-private, not type-private. These two declarations of dateFormatterUTC
have the same scope. Even in the first example, NSDate.dateFormatterUTC
is accessible throughout the entire file it’s declared in.
I do agree that the static version is preferable, but for stylistic reasons only: I like the way it’s indented right next to the thing that uses it.
As Gwendal wisely notes above, this approach assumes UTC
will only ever be called from one thread. Although static let
and global let
are both thread-safe in Swift, the Looks like it’s threadsafe starting in iOS 7. Phew.NSDateFormatter
class is not!
Still, always good to keep a thread safety warning next to any mention of singletons. If you do want to use a non-threadsafe helper object from multiple threads, consider either creating a new helper on every call, or using NSThread.currentThread().threadDictionary
to create a per-thread instance. Be sure to do a little profiling to make sure you’re actually solving a performance problem before opting for the more complex thread-local option.
Static vs class functions/variables in Swift classes?
static
and class
both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class
methods; they cannot override static
methods.
class
properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet.
Swift: Create utility methods as static class or regular functions?
It is largely subjective and there is no reason why you must pick one over the other.
That being said, some people favor the static method approach for organizational reasons, or as a form of namespacing. For example, using the static method approach also allows you to have a method ClassA.doSomething()
and a method named ClassB.doSomething()
.
Can you explain me the difference static and class in swift?
The difference between a function defined as static func
and another one defined as class func
is that static
is for functions of structures and enumerations, and class
is mainly for functions of protocols and classes.
Class functions can also be overridden by subclasses. For example:
class Animal{
class func generateAnimalSound(){
print("Some Animal Sound")
}
static func isAnimal() -> Bool{
return true
}
}
class Cat: Animal{
override class func generateAnimalSound(){
print("Meow!")
}
}
var someAnimal = Animal.generateAnimalSound() // prints "Some Animal Sound"
var cat = Cat.generateAnimalSound() // prints "Meow!"
However, if you try to override the static member function isAnimal()
, this will result in an error:
Cannot override static method
That's obviously because static methods cannot be overridden by subclasses. You should read the documentation provided both by Apple and other StackOverflow related questions:
- What is the difference between static func and class func in Swift?
static vs class as class variable/method (Swift)
The Swift Programming Language (Swift 3.1) - Methods
swift - how to declare a static class within the project
It's not the class itself, the contents must be marked as static
class Theme {
// static constant
static let foo = "foo"
// static variable
static var foo2 : String { return "foo2" }
// static method
class func bar(x: Int) -> Int
{
return 2 * x
}
}
let a = Theme.foo // "foo"
let b = Theme.foo2 // "foo2"
let y = Theme.bar(10) // 20
Make swift class conform to protocol - at static/class level
UPDATED for Swift Version 2.0 and above
As per Gregzo's answer, Swift 2.0+ allows methods to be declared as static in the protocol definition. These must be satisfied with static/class methods in objects that implement the protocol.
You cannot satisfy a protocol definition for a instance method with a static method or vice-versa, which makes this an incomplete answer for the question above.
If you want to try this just use the keyword "static" in your protocol definition for methods you will implement as static or class methods in your conforming objects:
protocol InstanceVsStatic {
func someInstanceFunc()
static func someStaticFunc()
}
enum MyConformingEnum: InstanceVsStatic {
case someCase
static func someStaticFunc() {
// code
}
func someInstanceFunc() {
// code
}
}
class MyConformingClass: InstanceVsStatic {
class func someStaticFunc() {
// code
}
func someInstanceFunc() {
// code
}
}
struct MyConformingStruct: InstanceVsStatic {
static func someStaticFunc() {
// code
}
func someInstanceFunc() {
// code
}
}
You can have an instance method call a static/class method:
This allows you to execute static code when you need to conform to a protocol that requires an instance method.
struct MyConformingStruct: InstanceVsStatic {
static func doStuffStatically(){
// code
}
static func someStaticFunc() {
// code
}
func someInstanceFunc() {
MyConformingStruct.doStuffStatically()
}
}
Swift 1.2
Other than indirectly as above, there is no way to use static (class) methods to conform to a protocol in pure swift version 1.2 and below. It is a known bug / unimplemented feature: https://openradar.appspot.com/20119848
Related Topics
How to Restrict the Type That a Function Throws in Swift
Result Values in '? :' Expression Have Mismatching Types 'Some View' and '...'
Uitesting Xcode 7: How to Tell If Xcuielement Is Visible
How to Remove Numbers from a String in Swift
Swift: Loop Over Array Elements and Access Previous and Next Elements
Firebase Firestore Not Updating Email Verification Status
Using Swift to Disable Sleep/Screen Saver for Osx
How to Set Countdowntimer Mode in Datepicker on Swiftui
Load a Collada (Dae) File into Scnnode (Swift - Scenekit)
Mkpointannotations Touch Event in Swift
Datepicker Using Time-Interval in Swiftui
How to Delete from Firebase Database
Swift Difference Between Final Var and Non-Final Var | Final Let and Non-Final Let
How to Properly Implement the Equatable Protocol in a Class Hierarchy
How to Change "Return" Key to "Done" on Keyboard with Swiftui
Convert Opengl Shader to Metal (Swift) to Be Used in Cifilter