Skip to content

Instantly share code, notes, and snippets.

@huangsam
Last active August 15, 2020 23:19
Show Gist options
  • Save huangsam/939e77fa7fb435b391fc2ee0f1a2a700 to your computer and use it in GitHub Desktop.
Save huangsam/939e77fa7fb435b391fc2ee0f1a2a700 to your computer and use it in GitHub Desktop.
Play around with Swift language
var multFour: [Int: Int] = [:]
for i in 1...3 {
multFour[i] = i * 4
}
typealias AnswerItem = Dictionary<Int, Int>.Element
typealias AnswerTuple = (Int, Int)
let sortedMultFour: [AnswerItem] = multFour.sorted { x, y in x.key < y.key }
for item: AnswerItem in sortedMultFour {
print("3 times \(item.key) is \(item.value)")
}
for (question, answer): AnswerTuple in sortedMultFour {
print("3 times \(question) is \(answer)")
}
// Create struct for a person
struct Person {
var name: String?
func sayHello() {
let name = self.name?.uppercased() ?? "NOBODY"
print("Hello! My name is " + name)
}
func saySomething(sayAction: () -> Void) {
sayAction()
}
func calculcateSomething(math: (Int, Int) -> Int, x: Int, y: Int) -> Int {
return math(x, y)
}
}
// Add an extension for Person struct
extension Person: CustomStringConvertible {
var description: String {
let name = self.name ?? "NOBODY"
return "Person with name '\(name)'"
}
}
// Define an optional Person
var person: Person?
// Define constant with UpperCamelCase convention
let MissingPerson = "Person does not exist"
// Toggle this to see how the code behaves
person = Person()
// Try basic operations
person?.sayHello()
person?.name = "John"
person?.sayHello()
print(person ?? MissingPerson)
// Try no-argument closure
person?.saySomething {
print("I am the best person there is")
}
// Define constants with UpperCamelCase convention
let BadPerson = -1001
let BadDivision = -1002
// Use add closure
let addResult = person?.calculcateSomething(math: { x, y in return x + y }, x: 3, y: 4)
print(addResult ?? BadPerson)
// Use sub closure
let subResult = person?.calculcateSomething(math: { $0 - $1 }, x: 3, y: 4)
print(subResult ?? BadPerson)
// Define a classic multiply function
func mult(x: Int, y: Int) -> Int {
return x * y
}
// Use multiply function
let multResult = person?.calculcateSomething(math: mult, x: 3, y: 4)
print(multResult ?? BadPerson)
// Define a divide closure
var div: (Int, Int) -> Int = { $1 != 0 ? $0 / $1 : BadDivision }
// Use divide closure with good inputs
let divResultGood = person?.calculcateSomething(math: div, x: 3, y: 4)
print(divResultGood ?? BadPerson)
// Use divide closure with bad inputs
let divResultBad = person?.calculcateSomething(math: div, x: 3, y: 0)
print(divResultBad ?? BadPerson)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment