Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Created March 29, 2017 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesrochabrun/cfeaf992ba7f8f5231264e6534ded062 to your computer and use it in GitHub Desktop.
Save jamesrochabrun/cfeaf992ba7f8f5231264e6534ded062 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
//GENERICS
//passing the reference in a method using the inout keyword
func swapInts(_ a: inout Int, _ b: inout Int) {
let tempA = a
a = b
b = tempA
}
var d = 10
var e = 20
swap(&d, &e)
var g = "james"
var h = "rochabrun"
//generic function
//a generic funtion uses a placeholder
func swapValues<T>(_ a: inout T, b: inout T) {
let tempA = a
a = b
b = tempA
}
swapValues(&g, b: &h)
//coding challenge
func clone<T>(item:T, numberOfTimes:Int) -> [T] {
var array = [T]()
for _ in 0..<numberOfTimes {
array.append(item)
}
return array
}
print(clone(item: 3, numberOfTimes: 4).count)
//multiple types generic function with a closure
func transform<T, U>(_ arg: T, operation: (T) -> U) -> U {
return operation(arg)
}
func stringToInt(_ a: String) -> Int {
guard let int = Int(a) else {fatalError()}
return int
}
func intToString(_ a: Int) -> String {
return String(a)
}
transform("7", operation: stringToInt)
transform(8, operation: intToString)
func map<T, U>(array: [T], transformation: (T) -> U) -> [U] {
var test = [U]()
for n in array {
test.append(transformation(n))
}
return test
}
func square(_ a: Int) -> Int {
return a * a
}
let numbers = [1, 2, 3, 4, 5]
map(array: numbers, transformation: square)
//PROTOCOL BASED TYPE CONSTRAINTS || generic types
//checking if a key exists based on its value
//here the constraimt is that the type of Value must conform the equatable protocol
func find<Key, Value: Equatable>(for value: Value, in dictionary: Dictionary<Key, Value>) -> Key? {
for (iterKey, iterValue) in dictionary {
if iterValue == value {
return iterKey
}
}
return nil
}
enum Snack {
case gum
case cookie
}
struct Item {
let price: Int
let quantity: Int
}
//creating an extensio of Item to conform the protocol
//to make it equatable we have to implement this function
extension Item : Equatable {
static func == (lhs: Item, rhs: Item) -> Bool {
return lhs.price == rhs.price && lhs.quantity == rhs.quantity
}
}
//this is a dictionary
let inventory: [Snack: Item] = [
.gum: Item(price: 1, quantity: 5),
.cookie: Item(price: 2, quantity: 3)
]
let someItem = Item(price: 1, quantity: 5)
//someItem is the value passed in and is been checke with the inventory , the return key is
find(for: someItem, in: inventory)
//CLASS BASED TYPE CONSTRAINTS
class Shape {
}
class Square: Shape {
}
func center<T: Shape>(of shape: T) {
print("method called")
}
let testShape = Shape()
let testSquare = Square()
center(of: testShape)
center(of: testSquare)
//this overcomplicates something a ssimple like
func shapeOf(_ shape: Shape) {
print("this is more than enough")
}
shapeOf(testSquare)
//coding challenge
func largest<T: Comparable>(in array: [T]) -> T? {
return array.max()
}
let arr = [1, 2, 3, 4, 5]
largest(in: arr)
//GENERIC TYPES SECOND SECTION
//LiNKED LISTS
//creating a linked list
//https://github.com/raywenderlich/swift-algorithm-club/tree/master/Select%20Minimum%20Maximum
class LinkedListNode<Key>{
let key: Key
var next: LinkedListNode?
weak var previous: LinkedListNode?
init(key: Key) {
self.key = key
}
}
class LinkedList<Element>: CustomStringConvertible {
typealias Node = LinkedListNode<Element>
private var head: Node?
//computed property
var first: Node? {
return head
}
var last: Node? {
if var node = head {
while node.next != nil {
node = node.next!
}
return node
} else {
return nil
}
}
//creating linked list operations
func append(_ value: Element) {
let new = Node(key: value)
if let lastNode = last {
lastNode.next = new
new.previous = lastNode
} else {
head = new
}
}
func node(atIndex index: Int) -> Node {
var node = head
var counter = 0
while node != nil {
if counter == index {
return node!
}
counter += 1
node = node!.next
}
fatalError("Index out of bounds")
}
func insert(_ value: Element, at index: Int) {
let nodeAtIndex = node(atIndex: index)
let nodeBeforeIndex = nodeAtIndex.previous
let new = Node(key: value)
new.previous = nodeBeforeIndex
new.next = nodeAtIndex
nodeAtIndex.previous = new
nodeBeforeIndex?.next = new
if nodeBeforeIndex == nil {
head = new
}
}
var description: String {
var output = "["
var node = head
while node != nil {
output += "\(node!.key)"
node = node!.next
if node != nil { output += ", " }
}
return output + "]"
}
}
let list = LinkedList<String>()
list.append("hola")
list.append("adios")
list.node(atIndex: 1)
list.node(atIndex: 0).key
//subclassing linkedlists
class LinkedIntegers: LinkedList<Int> {}
let newList = LinkedIntegers()
newList.append(1)
//coding challenge
struct Queue<Element> {
var array: [Element] = []
var isEmpty: Bool {
if array.count <= 0 {
return true
}
return false
}
var count: Int {
return array.count
}
mutating func enqueue(_ value: Element) {
array.append(value)
}
mutating func dequeue() -> Element? {
return array.removeFirst()
}
}
let enqueue = Queue<Int>()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment