Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Last active February 19, 2019 05:31
Show Gist options
  • Save jamesrochabrun/789c813706759d54905d4767a5c58835 to your computer and use it in GitHub Desktop.
Save jamesrochabrun/789c813706759d54905d4767a5c58835 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
//force unwrapping, bad code!
struct Person {
let firstName : String
let middleName: String?
let lastName: String
func fullName() -> String {
if middleName == nil {
return firstName + " " + lastName
} else {
return firstName + " " + middleName! + " " + lastName
}
}
}
let me = Person(firstName: "james", middleName: nil, lastName: "rocha")
me.middleName
//optional binding
let airpportCodes = ["CDG": "Charles dg"]
let newyorkairpot = airpportCodes["jfk"]
if let newyorkairpot = airpportCodes["jfk"] {
print(newyorkairpot)
} else {
print("this not exists")
}
let weatherDict: [String: [String: String]] = ["currently" : ["temperature": "22.3"] ,"daily" : ["temperature": "22.3"] , "weekly" : ["temperature": "22.3"]]
//bad
if let dailyWeather = weatherDict["daily"] {
if let highTemp = dailyWeather["temperature"] {
print(highTemp)
}
}
//correct
if let dailyWeather = weatherDict["daily"], let highTemperature = dailyWeather["temperature"] {
print(highTemperature)
}
//optional binding code challenge
let movieDictionary: [String: [String: Array]] = ["Spectre": ["cast": ["Daniel Craig", "Christoph Waltz", "Léa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]]]
var leadActor: String = ""
if let movieTitle = movieDictionary ["Spectre"], let movieActors = movieTitle["cast"]{
leadActor = movieActors[0]
}
//downsides of using if let
struct Friend {
let name : String
let age: String
let address: String?
}
//here we are returning nil checking for all the data and sometimes we need to check just for one var and pass the others
func new(friendDict: [String: String]) -> Friend? {
if let name = friendDict["name"], let age = friendDict["age"] {
let address = friendDict["address"]
return Friend(name: name, age: age, address: address)
} else {
return nil
}
}
//solution/ alternative
//EARLY EXIT USING GUARD
func newFriend(friendDict: [String: String]) -> Friend? {
guard let name = friendDict["name"], let age = friendDict["age"] else {
return nil
}
let address = friendDict["address"]
return Friend(name: name, age: age, address: address)
}
//failable init example
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
init?(dict: [String: String]) {
guard let title = dict["title"], let author = dict["author"] else {
return nil
}
self.title = title
self.author = author
self.price = dict["price"]
self.pubDate = dict["pubDate"]
}
}
let book = Book(dict: ["title" : "go",
"author": "author",
])
book?.title
//OPTIONAL CHAINING
//first take a look of how these classes doesn't give errors even that ont have initializers, its becuase they have default values or are optionasl, and that initialize the property to nil automatically, only with VAR with let dont make sense
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
}
class Residence {
var numberOfRooms = 1
var address: Address?
}
class Resident {
var residence: Residence?
}
let address = Address()
address.street
address.street = "el pulgar"
address.buildingName = "Building"
address.buildingNumber = "10"
let residence = Residence()
residence.address = address
let sasha = Resident()
sasha.residence = residence
if let home = sasha.residence, let postalAddress = home.address, let buildingNumber = postalAddress.buildingNumber, let convertedNumber = Int(buildingNumber) {
print((convertedNumber))
}
//optional chaining + optional binding to unwrap the optional constant
if let buildingnumber = sasha.residence?.address?.buildingNumber {
print(buildingnumber)
}
//PATTERN MATCHING WITH ENUMS
enum Coin: Double {
case penny = 0.01
case nickel = 0.05
case dime = 0.1
case quarter = 0.25
}
let wallet: [Coin] = [.penny, .penny, .nickel, .dime, .dime,.quarter, .dime, .dime,.dime, .quarter, .nickel]
var count = 0
for coin in wallet {
switch coin {
case .quarter: count += 1
default: continue // just continue and go to the next iteration
}
}
//beter written, this two codes are the same
count = 0
for case .quarter in wallet {
count += 1
}
//also with if statements example
for coin in wallet {
if case .nickel = coin {
print("not so much")
} else if case .dime = coin {
print("better than nothing")
}
}
//adn this is the same
for coin in wallet {
if coin == .nickel {
print("not so much")
} else if coin == .dime {
print("better than nothing")
}
}
//NIL COALESCING POPERATOR
let firstName: String? = nil
let userName = "@Passan"
//if firstname is not nil use firstName but if does use userName
let displayName = firstName ?? userName
print(displayName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment