call a private property on an instance of a class in swift

To call a private property on an instance of a class in Swift, you need to first define the property as private. This restricts the scope of the property to the class scope only.

Here's an example:

main.swift
class MyClass {
    private var myPrivateProperty = "Hello, World!"
    
    func printPrivateProperty() {
        print(myPrivateProperty)
    }
}

let instance = MyClass()
instance.printPrivateProperty() // Output: "Hello, World!"
233 chars
11 lines

In the above example, we have defined a MyClass that has a private property myPrivateProperty. The printPrivateProperty function is used to access the private property myPrivateProperty and print its value.

We create an instance of MyClass called instance and call the printPrivateProperty method on it which prints the value of the private property myPrivateProperty.

Note that if you try to access the private property myPrivateProperty directly outside the scope of the MyClass definition, it will result in a compilation error.

gistlibby LogSnag