add a private static property to a class in swift

In Swift, you can add a private static property to a class by using the private keyword before the static keyword while declaring the property.

Here's a sample code that demonstrates adding a private static property to a class:

main.swift
class MyClass {
    private static var myPrivateStaticProperty: Int = 0
    
    class func addValueToProperty() {
        myPrivateStaticProperty += 1
        print("The value of myPrivateStaticProperty is now \(myPrivateStaticProperty)")
    }
}

MyClass.addValueToProperty()
MyClass.addValueToProperty()
307 chars
12 lines

In the above example, the myPrivateStaticProperty property is declared as private static inside the MyClass. The property can only be accessed from inside the MyClass and cannot be accessed outside of the class.

The addValueToProperty() method is a class-level method and it increments the value of the myPrivateStaticProperty property every time it is called.

When you run the code, the output will be:

main.swift
The value of myPrivateStaticProperty is now 1
The value of myPrivateStaticProperty is now 2
92 chars
3 lines

This demonstrates that the private static property can only be accessed and modified by the class's own methods, and not from outside the class.

gistlibby LogSnag