import Cocoa
import Foundation
func sum<T: Numeric> (_ a: T, _ b: T) -> T {
a + bba
}
sum(1,2)
sum(1.2, 2.0)
let a: CGFloat = 10.2
let b: CGFloat = 2.3
sum(a,b)
struct Stack<T> {
private var = [T]()
mutating func push(_ element: T) {
elements.append(element)
}
mutating func pop() -> T? {
return elements.popLast()
}
func printStack() {
for i in stride(from: elements.count - 1, through:
0, by: -1) {
print("----\n| \(elements[i]) |")
}
print("-----------")
}
}
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.printStack()
struct PankCake{}
var stacker = Stack<PankCake>()
stacker.push(PankCake())
stacker.push(PankCake())
stacker.push(PankCake())
stacker.push(PankCake())
stacker.push(PankCake())
stacker.push(PankCake())
stacker.printStack()
// Extending generic structs
extension Stack {
var topItem: T? {
return(elements.isEmpty ? nil :
elements[elements.count - 1])
}
}
// With 2 generic parameters
struct HashMap<Key: Hashable, Value> {
private var storage: [Key: Value] = [:]
mutating func setValue(_ value: Value, forKey key:
Key) {
storage[key] = value
}
func getValue(forKey key: Key) -> Value? {
return storage[key]
}
mutating func removeValue(forKey key: Key) {
storage[key] = nil
}
}
var hashMap = HashMap<Int, String>()
hashMap.setValue("25", forKey: 1)
hashMap.setValue("30", forKey: 2)
hashMap.getValue(forKey: 1)
//final class LinkedNode {
// var val: Int
// var next: LinkedNode?
//
// init(val: Int) {
// self.val = val
// }
//}
//
//
//
//final class ReverseLinkedList {
// static func reverse(_ node: LinkedNode?) ->
LinkedNode? {
// guard let node = node else { return nil }
// var nextNode = node.next
// var currentNode = LinkedNode(val: node.val)
//
// while nextNode != nil {
// let newNode = LinkedNode(val:
nextNode!.val)
// newNode.next = newNode
//
// currentNode = newNode
// nextNode = nextNode?.next
// }
// return currentNode
// }
//}
//
//var linkedNode = LinkedNode(val: 1)
//linkedNode.next = LinkedNode(val: 2)
//
//linkedNode.next?.next = LinkedNode(val: 3)
//linkedNode.next?.next?.next = LinkedNode(val: 4)
//linkedNode.next?.next?.next = LinkedNode(val: 5)
//
//
//let answer = ReverseLinkedList.reverse(linkedNode)
//
//print("rootNode \(String(describing: answer?.val))")
//print("rootNode \(String(describing:
answer?.next?.val))")
//print("rootNode \(String(describing:
answer?.next?.next?.val))")
//print("rootNode \(String(describing:
answer?.next?.next?.next?.val))")
// fizzbuzz for one
let score = 10
let reallyBig = 10__00__0_000
print(reallyBig)
let lowerScore = score-2
let higherScore = score+10
let doubledScore = score*2
let halvedScore = score*score
var counter = 10
counter += 5
counter *= 2
counter *= 3
let number = 120
print(number.isMultiple(of: 3))
let a1 = 1
let b1 = 2.0
let c1 = a1 + Int(b1)
var name = "Kumar Utsav"
var nameList = ["Bush", "Obama", "Trump", "Biden"]
//print(nameList.sorted())
print(nameList.reversed())
let reverseList = nameList.reversed()
print(reverseList)
name = "John Travolta"
var rating = 5.0
rating *= 2
let fileName = "paris.jpg"
print(fileName.hasSuffix(".jpg"))
var isAuthenticated = false
isAuthenticated = !isAuthenticated
print(isAuthenticated)
isAuthenticated = !isAuthenticated
print(isAuthenticated)
var gameOver = false
print(gameOver)
gameOver.toggle()
print(gameOver)
let firstPart = "Hello, "
let secondPart = "world!"
let greeting = firstPart + secondPart
print(greeting)
let localizedGreeting = "Bonjour Tout Le Monde"
let dict = [greeting: localizedGreeting]
print("The greeting in English is \(greeting)")
print("The greeting in French is \(localizedGreeting)")
if let myGreeting = dict[greeting] {
print("The localized greeting in French is \
(myGreeting)")
}
//guard let monGreeting = dict[greeting] else { return }
//print("The localized greeting in romantic language is \
(monGreeting)")
let people = firstPart + "yes"
let luggageCode = "1" + "2" + "3"
let quote = " Then he tapped a sign saying \"Believe\"
and walked away"
print(quote)
let nameActor = "Taylor"
let age = 26
let message = "Hello , my name is \(nameActor) and
I'm on a tour and I'm \(age) years old. "
let luggageArray = Array(luggageCode)
print(luggageArray.count)
for(index, value) in luggageArray.enumerated() {
print(index, value, index + 1, String(value) +
String("9"))
}
let numbers = 11
let missionMessage = "Appollo \( String(numbers))
landed on the moon."
enum value: Int, Equatable {
typealias RawValue = Int
case one, two, three, four
// switch value.self {
// case one:
// return one.rawValue
// case two:
// return two.rawValue
// case three:
// return three.rawValue
// case four:
// return four.rawValue
//
// }
}
var beatles = ["John", "Kumar", "Lava", "Halwa"]
var number12 = [4,6,8,12,23,45]
var temperatures:[Any] = [25.3, 28.2, 26.4]
print(beatles[value.three.rawValue])
print(temperatures[2])
print(number12[1])
beatles.append("Utsav")
print(beatles)
beatles.remove(at: 3)
print(beatles)
beatles.append(contentsOf: ["one", "two"])
print(beatles)
extension Array {
mutating func appendGeneric<T>(_ value: T) {
if let castedValue = value as? Element {
self.append(castedValue)
} else {
print("Type mismatch : Cannot append \
(type(of: value))to array of \(Element.self)")
}
}
}
//extension Array {
// mutating func appendGeneric<T>(_ value: T) {
// // Check if the array type matches the type of
the value being appended
// if let castedValue = value as? Element {
// self.append(castedValue)
// } else {
// print("Type mismatch: Cannot append \
(type(of: value)) to array of \(Element.self)")
//
// }
// }
//}
var intArray = [1,2,3]
print("Initial Array: \(intArray)")
// Append an integer (works)
intArray.appendGeneric(4)
print("After appending 4: \(intArray)")
temperatures.appendGeneric(34.0)
print("After appending 34.0 : \(temperatures)")
temperatures.append("Bonjour")
print(temperatures)
var employee = ["Taylor Swift", "Singer", "Nashville"]
let employee2 = ["name" : "Taylor Swift", "job":
"Singer", "locaton": "Nashville"]
print("the value is \(employee2["name", default:
"Unknown"])")
print("the value is \(employee2["job", default:
"Unknown"])")
print("the value is \(employee2["locaton", default:
"Unknown"])")
let hasGraduated = ["Eric": false, "Maverick": true,
"Otis"
:false]
print("The list of graduated kids are \
(hasGraduated.keys.sorted())")
print(employee2["name", default: "unknown"])
var heights = [String: Int]()
heights["Yao Ming"] = 229
heights["Shaquilla"] = 226
heights["Lebron James"] = 206
heights
var archEnemies = [String: String]()
archEnemies["Batman"] = "The Joker"
archEnemies["Superman"] = "Loca"
archEnemies
archEnemies["Batman"] = "Peter"
archEnemies
let pope = Set(["kumar", "utsav", "loca", "kumar"])
pope
var opium = Set<String>()
opium.insert("Heroin")
opium.insert("Tomb")
opium.insert("Nicolas")
var selected = "Monday"
selected = "Tuesday"
selected = "January"
enum Weekday {
case monday
case tuesday
case wednesday
case thursday
case friday, saturday, sunday
}
var day = Weekday.monday
day = .sunday
print("Today is \(day)")
let surname: String = "Lasso"
var scores: Double = 0
let playerName: String = "Roy"
var luckyNumber: Int = 13
let pi: CLongDouble = 3.14159265358979323846
//let pi: Double = .pi
print(pi)
var albums: [String] = ["Red", "Fearless"]
// create some values
let d1 = 1.2
let d2 = 0.0
let d3 = Double.infinity * 0.0
let d4 = Double.infinity
let d5 = Double.nan * 2
// check if Not a Number
print(d1.isNaN) // false
print(d2.isNaN) // false
print(d3.isNaN) // true
print(d4.isNaN) // false
print(d5.isNaN) // true
print(log10(10.0))
print(log10(50.0))
var dict24 = [Int: Double]()
for i in 1..<100 {
let counter = 0.0
dict24[i] = log10(Double(i))
print("The logarithmic table for number \(i) is \
(log10(Double(i) + counter))")
}
let fileNames = "example.txt"
let content = dict24
// get the path for the document directory of the app
if let documentDirectory =
FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first {
// create a file path with the desired file name
let fileURL =
documentDirectory.appendingPathComponent(fileName
s)
do {
// write the contents to the file
try content.description.write(to: fileURL,
atomically: true, encoding: .utf8)
print("File written successfully at path: \
(fileURL.path)")
} catch {
// Handle error if something goes wrong
print("Failed to write to file : \
(error.localizedDescription)")
}
} else {
print("Could not write into the document directory")
}