Skip to content

Instantly share code, notes, and snippets.

@thanhluu
Created May 1, 2016 14:27
Show Gist options
  • Save thanhluu/bc685c50fa13bba4fdc30d82a2c88f51 to your computer and use it in GitHub Desktop.
Save thanhluu/bc685c50fa13bba4fdc30d82a2c88f51 to your computer and use it in GitHub Desktop.
Optionals
struct Person {
let firstName: String
let middleName: String?
let lastName: String
func getFullName() -> String {
if middleName == nil {
return firstName + " " + lastName
} else {
return firstName + " " + middleName! + " " + lastName
}
}
}
let me = Person(firstName: "Pasan", middleName: nil, lastName: "Premaratne")
me.getFullName()
let airportCodes = ["CDG": "Charles de Gaulle"]
if let newYorkAirport = airportCodes["JFK"] {
print(newYorkAirport)
} else {
print("Whoops that key does not exist!")
}
let weatherDictionary: [String: [String: String]] = ["currently": ["temperature": "22.3"], "daily": ["temperature": "22.3"], "weekly": ["temperature": "22.3"]]
if let dailyWeather = weatherDictionary["daily"], let highTemperature = dailyWeather["temperature"] {
print(highTemperature)
}
// Bai Tap
let movieDictionary = ["Spectre": ["cast": ["Daniel Craig", "Christoph Waltz", "Léa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]]]
var leadActor: String = ""
// Enter code below
if let spectre = movieDictionary["Spectre"], let cast = spectre["cast"] {
var leadActor = cast[0]
}
struct Friend {
let name: String
let age: String
let address: String?
}
func createFriend(dict: [String: String]) -> Friend? {
// if let name = dict["name"], let age = dict["age"] {
// let address = dict["address"]
// return Friend(name: name, age: age, address: address)
// } else {
// return nil
// }
guard let name = dict["name"], let age = dict["age"] else {
return nil
}
let address = dict["address"]
return Friend(name: name, age: age, address: address)
}
// Bai tap
struct Book {
let title: String
let author: String
let price: String?
let pubDate: String?
init?(dict: [String: String]) {
guard let title = dict["title"], author = dict["author"] else {
return nil
}
self.title = title
self.author = author
self.price = dict["price"]
self.pubDate = dict["pubDate"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment