Skip to content

Instantly share code, notes, and snippets.

@byJeevan
Last active June 7, 2020 19:40
Show Gist options
  • Select an option

  • Save byJeevan/29f1e20cf0a07e961e982890bd9c53a3 to your computer and use it in GitHub Desktop.

Select an option

Save byJeevan/29f1e20cf0a07e961e982890bd9c53a3 to your computer and use it in GitHub Desktop.
Explore swift APIs that reduces lots of code effort
@byJeevan
Copy link
Author

byJeevan commented May 25, 2020

4. Stack implementation (LIFO)

`

//Stack implementation (LIFO)
struct Stack {
    
    private var stackArray:[String] = []  
  
   func peak() -> String? {
        return self.isEmptyStack() ? nil : stackArray.first
    }
    
    mutating func pop() -> String? {
        return self.isEmptyStack() ? nil : stackArray.removeFirst() //returns removed element
    }
    
    mutating func push(element:String) {
        stackArray.append(element)
    }
    
    func isEmptyStack() -> Bool {
        return stackArray.count == 0
    }
}

extension Stack: CustomStringConvertible {
    var description: String {
        let topLogString = "-----STACK----- \n"
        let bottomLogString = "\n------*--------\n"
        let middleLogString = stackArray.joined(separator: "\n")
        return topLogString + middleLogString + bottomLogString
    }
}

//Testing
var stackTest = Stack()
stackTest.push(element: "Eleo")
stackTest.push(element: "Combo")
stackTest.push(element: "Rambo")

print(stackTest)
/*
-----STACK----- 
Eleo
Combo
Rambo
------*--------
*/
stackTest.peak()
stackTest.pop()
/*
-----STACK----- 
Combo
Rambo
------*--------
*/
print(stackTest)


`

//BONUS: Implement generic type of stack

@byJeevan
Copy link
Author

byJeevan commented Jun 7, 2020

Using Enums :

  • with combining Tuples for complex data structure.
  • Polymorphism representation of collections ex. Array. That gives compile time safety check.
  • Stay away from hierarchical architecture (means avoids subclass). Where we can add additional type with new property without re-arranging super class properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment