add a private property to a class in swift

To add a private property to a class in Swift, you can use the private keyword followed by the property declaration within the class. This makes the property only accessible within the class and not outside of it.

Here's an example:

main.swift
class MyClass {
    
    private var myPrivateProperty: String
    
    init(myPrivateProperty: String) {
        self.myPrivateProperty = myPrivateProperty
    }
    
    // other class methods and properties
}
212 chars
11 lines

In this example, myPrivateProperty is a private property of MyClass and can only be accessed within the class. The init() method is used to set the value of the private property.

Using private properties in classes promotes encapsulation and helps organize code by clearly defining which properties and methods are internal to the class and which are meant to be exposed to other classes or external code.

gistlibby LogSnag