Swift Programming: The Power of WillSet in Real-World Scenarios

Abdullah Bilgin
Swift Insights
Published in
3 min readNov 18, 2023

In the dynamic world of Swift programming, the willSet property observer plays a crucial role in various real-world scenarios. Let's explore its applications in different contexts:

1. Validating User Profiles

class UserProfile {
var userName: String {
willSet {
if newValue.isEmpty {
print("Username cannot be empty. Please enter a valid username.")
}
}
}

init(userName: String) {
self.userName = userName
}
}

var user1 = UserProfile(userName: "Abdullah")
user1.userName = ""

Explanation:

  • The UserProfile class has a property userName with a willSet observer.
  • It checks if the new value being set is empty in the willSet block and prints a message if it is.
  • The initialization ensures that the username is initially set to a non-empty value.

2. Database Updates

class Product {
var productName: String {
willSet {
// Sends a real database update for the product name to DatabaseManager.
DatabaseManager.shared.updateProductInDatabase(name: newValue)
}
}

init(productName: String) {
self.productName = productName
}
}

class DatabaseManager {
static let shared = DatabaseManager()
var data: String = ""

init() {}

func updateProductInDatabase(name: String) {
print("Updating product name in the database: \(name)")
data = name
// Real update operations would be performed here.
}
}

var data = DatabaseManager()
var product = Product(productName: "Smartphone")
product.productName = "Updated Smartphone"

Explanation:

  • The Product class has a property productName with a willSet observer.
  • In the willSet block, it calls a function in DatabaseManager to update the product name in the database.
  • Demonstrates using willSet to trigger actions when a property is about to be updated.

3: UI Updates

class WeatherDisplay {
var temperature: Double {
willSet {
// Using UIUpdater class instead of actual UI update for demonstration.
UIUpdater.shared.updateTemperatureDisplay(newTemperature: newValue)
}
}

init(temperature: Double) {
self.temperature = temperature
}
}

class UIUpdater {
static let shared = UIUpdater()

private init() {}

func updateTemperatureDisplay(newTemperature: Double) {
print("UI updated: \(newTemperature) degrees")
// Actual UI update operations would be performed here.
}
}

var weather = WeatherDisplay(temperature: 25.0)
weather.temperature = 28.5 // UI updated: 28.5 degrees

Explanation:

  • The WeatherDisplay class has a property temperature with a willSet observer.
  • In the willSet block, it calls a function in UIUpdater to update the temperature display.
  • Illustrates how willSet can be used to seamlessly update the UI based on property changes.

4. Logging and Error Tracking

class PaymentProcessor {
var transactionAmount: Double {
willSet {
// Using Logger class instead of actual logging for demonstration.
Logger.shared.logPaymentTransaction(amount: newValue)
}
}

init(transactionAmount: Double) {
self.transactionAmount = transactionAmount
}
}

class Logger {
static let shared = Logger()

private init() {}

func logPaymentTransaction(amount: Double) {
print("Payment transaction logged: \(amount) TL")
// Actual logging operations would be performed here.
}
}

var paymentProcessor = PaymentProcessor(transactionAmount: 50.0)
paymentProcessor.transactionAmount = 75.0 // Payment transaction logged: 75.0 TL

Explanation:

  • The PaymentProcessor class has a property transactionAmount with a willSet observer.
  • In the willSet block, it calls a function in Logger to log the payment transaction.
  • Demonstrates using willSet for logging and tracking activities before a property is updated.

5. Monitoring and Analytics

class WebsiteAnalytics {
var userVisits: Int {
willSet {
// Using AnalyticsTracker class instead of actual analytics for demonstration.
AnalyticsTracker.shared.sendUserVisitsReport(visits: newValue)
}
}

init(userVisits: Int) {
self.userVisits = userVisits
}
}

class AnalyticsTracker {
static let shared = AnalyticsTracker()

private init() {}

func sendUserVisitsReport(visits: Int) {
print("User visits report sent: \(visits)")
// Actual monitoring and analytics operations would be performed here.
}
}

var analytics = WebsiteAnalytics(userVisits: 1000)
analytics.userVisits = 1200 // User visits report sent: 1200

Explanation:

  • The WebsiteAnalytics class has a property userVisits with a willSet observer.
  • In the willSet block, it calls a function in AnalyticsTracker to send a report of user visits.
  • Shows how willSet can be used for monitoring and analytics, capturing changes before they occur.

https://github.com/abilgin88/SwiftCompendium

In Swift’s Embrace: Elevating User Experiences

In the realm of Swift programming, these snippets showcase the language’s prowess. From validation checks to real-time updates, Swift’s willSet property observer proves invaluable. Each example unveils the language's versatility in crafting user-friendly applications.

Gratitude for joining this Swift journey! Your dedication to mastering Swift is commendable. Swift isn’t just a language; it’s a gateway to crafting exceptional user experiences. Happy coding! 🚀🍏

--

--

Abdullah Bilgin
Swift Insights

"iOS engineer & IT head, crafting code & innovation. Leading with tech prowess & strategic vision. Bridging iOS dev & IT realms. Lifelong learner. 📱💡"