Skip to content

Instantly share code, notes, and snippets.

View piyushdec's full-sized avatar

Piyush piyushdec

  • United States
View GitHub Profile
//to register to catch a notification being posted, use this:
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(userLoggedIn), name: Notification.Name("UserLoggedIn"), object: nil)
let aMovement = Movement.left
switch aMovement {
case .left: print("left")
default: ()
}
if case .left = aMovement {
print("left")
}
// Mapping to Integer
enum Movement: Int {
case left = 0
case right = 1
case top = 2
case bottom = 3
}
// You can also map to strings
enum State: String {
// mercury = 1, venus = 2, ... neptune = 8
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// North = "North", ... West = "West"
enum CompassPoint: String {
case north, south, east, west
}
enum Device {
enum Phone {
case iPhone
case pixel
case galaxy
case prius
}
enum Laptop {
case macbook
case chromebook
let device = Device.googleHome
let phone = Device.Phone.iPhone
let laptop = Device.Laptop.chromeBook
struct Device {
enum Phone {
case iPhone
case pixel
case galaxy
case prius
}
enum Laptop {
case macbook
case chromebook
enum Trade {
case buy(stock: String, amount: Int)
case sell(stock: String, amount: Int)
}
func trade(type: Trade) {}
//If you want to access this information, again, pattern matching comes to the rescue:
let trade = Trade.buy(stock: "APPL", amount: 500)
if case .buy(stock, amount) = trade {
print("buy \(amount) of \(stock)")
}
let tp = (stock: "TESLA", amount: 100)
let trade = Trade.sell(tp)
if case .sell(stock, amount) = trade {
print("buy \(amount) stocks of \(stock)")
}
//prints: "buy 100 stocks of TESLA