Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developer-shubham101/cdacfd33ab87e55d62d06fe72b33b09c to your computer and use it in GitHub Desktop.
Save developer-shubham101/cdacfd33ab87e55d62d06fe72b33b09c to your computer and use it in GitHub Desktop.
Swift Key Path Expressions Example
//
// 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