Skip to content

Instantly share code, notes, and snippets.

@saamerm
Created January 3, 2020 09:37
Show Gist options
  • Save saamerm/8dfe6f105f749398aca310d01dc4cc27 to your computer and use it in GitHub Desktop.
Save saamerm/8dfe6f105f749398aca310d01dc4cc27 to your computer and use it in GitHub Desktop.
Just another swift cheat sheet
// CheatSheet
// FUNCTIONS
func Main(){
Hello()
}
func Hello(){
print("WHAT")
}
Main()
// ARRAYS
// =======
print ("ARRAYS")
var arr: [Int]
arr = [1,2,3,4,5]
// Same as
var array: Array<Int> = [1,2,3,4,5]
var emptyArray = [Int]()
print("The array has \(emptyArray.count) elements") // Cannot use .. + count + ...
// Adding an element to the array
emptyArray.append(5)
print(emptyArray.first ?? "as") // Since the type of first is a Int? (optional), so we provide a default value if it is nil
print(emptyArray.first!) // or we can "unwrap" it
print(emptyArray.first) // Prints Optional(5) because "Expression implicitly coerced from 'Int?' to 'Any'"
print(emptyArray.first as Any) // Prints Optional(5)
// Emptying the array again
emptyArray=[]
print(emptyArray.first ?? "as") // Prints "as" aka default value
if !emptyArray.isEmpty{
print(emptyArray.first!) // Without check gives- Fatal error: Unexpectedly found nil while unwrapping an Optional value: file BST.playground
}
print(emptyArray.first) // Prints "nil"
print(emptyArray.first as Any) // Prints "nil"
var array2 = Array(repeating: 2, count: 3) // Different types of Array init
print (array2)
var array3 = Array(1...3) // Sequence of values with 3 .'s
print(array3)
// LOOPS
// =======
print ("\nLOOPS")
import Foundation // Needed for random number creator arc4random
var x: UInt32
var y: UInt32
for element in arr
{
print (element)
x = arc4random()
print (x)
y = arc4random_uniform(10)
print (y)
}
// BST
// =======
print ("\nBST")
class TreeNode{
var Left: TreeNode?
var Right: TreeNode?
var Value: Int
init(value: Int, left: TreeNode? = nil, right: TreeNode? = nil){
Value = value
Left = left
Right = right
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment