Created
May 20, 2022 10:54
-
-
Save developer-shubham101/cdacfd33ab87e55d62d06fe72b33b09c to your computer and use it in GitHub Desktop.
Swift Key Path Expressions Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// KeyPathExampleViewController.swift | |
// UpgradeMySelf-ios | |
// | |
// Created by Shubham Sharma on 09/05/22. | |
// Copyright © 2022 Shubham Sharma. All rights reserved. | |
// | |
import UIKit | |
struct Car { | |
var name: String | |
var kind: String | |
} | |
class KeyPathExampleViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
tabBarItem.tag = TabbarItemTag.firstViewController.rawValue | |
self.view.backgroundColor = .white | |
print("Key paths Example-----") | |
let keyPath = \Car.name // Create key path | |
var audi = Car(name: "Audi", kind: "luxury") // Create instance of class or struct | |
print(audi[keyPath: keyPath]) // Access the value of instance | |
audi[keyPath: keyPath] = "Audi A8 L" // Update the value of instance | |
print(audi[keyPath: keyPath]) | |
print(audi[keyPath: \.kind]) // Short hand version of key path | |
let cars = [ | |
audi, | |
Car(name: "Škoda", kind: "comfort") | |
] | |
let carNameList = cars.map(\.name) // in Swift 5.2 we can pass key path as function | |
print(carNameList) | |
print("End of Key paths Example-----") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment