How to access static properties in a struct in Swift

1 Answer

0 votes
import Foundation 

struct Configuration {
    private static var _environment: String = "production"

    public static var environment: String {
        get {
            return _environment
        }
        set {
            // Now recognized via Foundation
            let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
            if !trimmed.isEmpty {
                _environment = trimmed
            }
        }
    }

    public static func printEnvironmentDetails() {
        print("Active environment status: \(_environment)")
    }
}

// --- Example Usage ---

// 1. Accessing the static property directly via the Type Name (Best Practice)
print("Current Environment: \(Configuration.environment)")

// 2. Calling a static function
Configuration.printEnvironmentDetails()

// 3. Modifying the static property
Configuration.environment = "staging"
print("Updated Environment: \(Configuration.environment)")

/* 
 * Note on Instances:
 * let configInstance = Configuration()
 * print(configInstance.environment) // Error: Static member 'environment' cannot be used on instance of type 'Configuration'
 */


/*
run:

Current Environment: production
Active environment status: production
Updated Environment: staging

*/

 



answered 6 days ago by avibootz
...