Skip to content

Instantly share code, notes, and snippets.

View dineshba's full-sized avatar
👨‍💻
Trying to be an OSS contributor

Dinesh B dineshba

👨‍💻
Trying to be an OSS contributor
View GitHub Profile
enum Taste {
case sweet
case bitter
case sour
case spicy
case salty(Int)
}
extension Eatable {
func isBitter() -> Bool {
return self.taste == .bitter
}
}
struct Sugar: Eatable {
var taste: Taste = .sweet
}
struct Programmer {
let brain: Brain
let laptop: Laptop?
let name: String
}
struct Brain {
}
struct Laptop {
let name: String
let fan: Fan?
let a = 5 // Int
let b = 5.0 // Double
let c = Float(5.3) // Float
let sugar = Sugar(taste: .sweet) // Sugar
let sweet = Taste.sweet // Taste
let sour: Taste = .sour // Taste
let sum = sum(5, nil) // Int?
let firstValue = [1,2,3].first // Int?
// mandatory argument names for caller
func add(augend: Int, addend: Int) -> Int {
return augend + addend
}
let sum = add(augend: 5, addend: 2)
// no argument names for caller (underscore for no name)
func add(_ augend: Int, _ addend: Int) -> Int {
return augend + addend
}
struct Square {
let size: Int
var area: Int { // var computedProperty: ReturnType {
return size * size // return (compute from other instance variables)
} // }
var perimeter: Int {
return 4 * size
}
extension Double { //swift class
func half() -> Double {
return self / 2
}
}
1.3.half() //0.6500000000000000
1000.0.half() // 500
Double(999).half() // 499.5
if let laptop = programmer.laptop { // set the value of laptop if `programmer.laptop` is not nil and
// enter into if-case or enter into `else` case.
if let laptopFan = laptop.fan { // set the value of laptopFanName if `laptop.fan` is not nil and
// enter into if-case or enter into `else` case.
print("\(laptop.name) contains \(laptopFan.name) fan")
} else {
print("\(laptop.name) contains no fan") // Note: String interpolation "\(value)"
}
} else {
print("\(programmer.name) have no laptop")
func printSummary(_ programmer: Programmer) {
guard let laptop = programmer.laptop else { // set the value of laptop if `programmer.laptop` is not nil
print("\(programmer.name) have no laptop") // and will go line 6. If `programmer.laptop` is nil, it will
return // enter into else case and return to caller of this function.
}
guard let laptopFan = laptop.fan else { // Syntax
print("\(laptop.name) contains no fan") // guard let constant = expression else {
return // return returnValue
} // }
print("\(laptop.name) contains \(laptopFan.name) fan")