Skip to content

Instantly share code, notes, and snippets.

View agoiabel's full-sized avatar

Agoi Abel Adeyemi agoiabel

View GitHub Profile
func dayType(for day: String) -> String {
switch day {
case: "Saturday", "Sunday": return "Weekend"
case: "Monday", "Tuesday", "Wednessday", "Thursday", "Friday": return "Weekday"
default: return "This is not a valid date"
}
}
let result1 = dayType(for: "Sunday") //will return "Weekend"
enum Day {
case Sunday
case Monday
case Tuesday
case Wednessday
case Thursday
case Friday
case Saturday
}
/** Rewriting the date type function */
func dayType(for day: Day) {
switch day {
case .Saturday, .Sunday:
return "Weekend"
case .Monday, .Tuesday, .Wednessday, .Thursday, .Friday
return "Weekday"
}
}
// You can also map to strings
enum Week: String {
case Sunday = "Weekday"
case Monday = "Weekday"
case Tuesday = "Weekday"
case Wednessday = "Weekday"
case Thursday = "Weekday"
case Friday = "Weekend"
case Saturday = "Weekend"
/** associate without labels */
enum Trade {
case Buy(String, amount)
case Sell(String, Int)
}
Trade.Buy("Firstbank PLC", 300)
Trade.Sell("Firstbank PLC", 700)
/** associate with labels */
enum AppleDevice {
case iPad
case iPhone
case AppleTv
case AppleWatch
func description() -> String {
return "This is an apple device"
}
}
enum AppleDevice {
case iPad, iPhone, AppleTv, AppleWatch
func description() -> String {
switch self {
case .iPad: return "\(self) was introduced 2006"
case .iPhone: return "\(self) was introduced 2007"
case .AppleTv: return "\(self) was introduced 2010"
case .AppleWatch: return "\(self) was introduced 2014"
}
class Street {
var streetName: String?
}
class House {
var noOfRooms = 1
var street: Street?
}
class Person {
var house: House?
}
if let myHouse = Person.house, let myStreet = myHouse.street {
print(myStreet) //this will access the street
}
//if the Person.house fails, it wil not get to the street
//which can either return a null or the street
let myStreet = Person.house?.street
//to make sure we get a value, we can include the if let like below
if let myStreet = Person.house?.street {
print(myStreet)
}