Posts

Showing posts from March, 2024

Exploring Different Data Observers and Use Cases with Code

Image
Exploring Different Data Observers and Use Cases with Code 1. Protocol/Delegate Pattern: 🔍 Understanding the Scenario: Suppose we have a scenario where we need to notify a ViewController whenever a new item is added to a shopping cart. We'll use the protocol/delegate pattern to achieve this. 📝 Protocol Definition: protocol ShoppingCartDelegate: AnyObject { func didAddItemToCart(itemName: String) } 🛒 Shopping Cart Class: class ShoppingCart { weak var delegate: ShoppingCartDelegate? func addItemToCart(itemName: String) { // Add item to cart logic delegate?.didAddItemToCart(itemName: itemName) } } 👩‍👧‍👦 View Controller Implementation: class ViewController: UIViewController, ShoppingCartDelegate { let shoppingCart = ShoppingCart() override func viewDidLoad() { super.vie...

Comparing Filter, Map, and Find in Swift and JavaScrip

Image
Comparing Filter, Map, and Find in Swift and JavaScript In this blog post, we'll explore how to use three fundamental array methods, filter , map , and find , in both Swift and JavaScript. We'll compare the shorthand notation ( $0 , $1 , etc.) used in Swift with the named parameter notation for increased clarity and readability. Filter in Swift: let numbers = [1, 2, 3, 4, 5] // Using $0 shorthand notation let evenNumbers = numbers.filter { $0 % 2 == 0 } // Output: [2, 4] // Using named parameter notation let oddNumbers = numbers.filter { number in return number % 2 != 0 } // Output: [1, 3, 5] Filter in JavaScript: const numbers = [1, 2, 3, 4, 5]; // Using anonymous function const evenNumbers = numbers.filter(num => num % 2 === 0); // Output: [2, 4] // Using named function const oddNumbers = numbers.filter(function(num) { return num % 2 !== 0; }); // Output: [1, 3, 5] Map in Swift: let numbers...