Skip to content

Instantly share code, notes, and snippets.

Operation Performance (> means shorter time)
Initilization Array > Set
Iteration Set > Array
Count Set = Array
Check Empty Set = Array
Find Element Existence or Index Set > Array
Find Min & Max Set > Array
Sort Elements Set = Array
Add Element Set = Array
Remove Element(s) Set = Array
let tuple0 = () // inferred as Void
let tuple1 = (1, ["three"]) // inferred as (Int, [String])
let tuple2 = (4, true, "Two") // inferred as (Int, Bool, String)
let tuple3 = ("a", tuple1) // inferred as (String, (Int, [String]))
let jan = (1, "January")
print("Order in a year: \(jan.0)")
// Prints "Order in a year: 1"
print("Month full name: \(jan.1)")
// Prints "Month full name: January"
let jan = (1, "January")
let (order, fullName) = jan
//alternatively, you can combine the above: let (order, fullName) = (1, "January")
print("Order is \(order)")
//Prints "Order is 1"
print("Full name is \(fullName)")
//Prints "Full name is January"
let jan = (order: 1, fullName: "January")
print("Order is \(jan.order)")
//Prints "Order is 1"
print("Full name is \(jan.fullName)")
//Prints "Full name is January"
func describeWeekday(_ weekday: (order: Int, name: String)) {
print("Day \(weekday.order) in a week is \(weekday.name)")
}
describeWeekday((0, "Sunday"))
// Prints "Day 0 in a week is Sunday"
func retrieveStudentRecord(studentId: Int) -> (name: String, age: Int)? {
// search the database using the provided student Id, arbitray conditions for demo purpose
if studentId < 10000 {
print("Didn't find the student with id: \(studentId)")
let student: Dictionary<String, Any> = ["name": "John", "age": 14, "gender": "Male"]
for item in student {
print("For key: \(item.key), the value is \(item.value)")
}
// Prints the following lines:
// For key: name, the value is John
// For key: gender, the value is Male
// For key: age, the value is 14
var numbers: Set = [1, 2, 3, 4, 5]