0% found this document useful (0 votes)
31 views34 pages

Final all codes of Paul Hudson on swift

Uploaded by

avecutsav3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views34 pages

Final all codes of Paul Hudson on swift

Uploaded by

avecutsav3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 34

import Cocoa

import Foundation

func sum<T: Numeric> (_ a: T, _ b: T) -> T {


a+b
}

sum(1,2)
sum(1.2, 2.0)
let a:
sum(a,b)

struct Stack<T> {
private var elements = [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") == true)
print(fileName.hasSuffix(".jpg") == false)

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))")
}
var myContent7 = [String]()
for i in 1...12 {
print("The \(i) times table")
for j in 1...12 {
print(" \(j) x \(i) is \(j * i)")
myContent7.append(" \(j) x \(i) is \(j * i)")
}
}

myContent7

let fileNames = "example.txt"


let tableName = "table.txt"
let multContent = myContent7
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)
let fileURL7 =
documentDirectory.appendingPathComponent(tableNa
me)

do {
// write the contents to the file
try content.description.write(to: fileURL,
atomically: true, encoding: .utf8)
try multContent.description.write(to: fileURL7,
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")
}

var user:[String: String] = ["id": "@twoStraws"]


var books: Set<String> = Set(["The blue eye",
"Foundation", "Girl", "Foundation", "woman"])

var soda: [String] = ["Coke", "Pepsi", "Irn-Brui"]

var teams: [String] = [String]()


var clues = [String]()

enum UIStyle {
case light, dark, system
}

var style = UIStyle.light


style = .dark

let username: String


// lots of complex logic
if true == true {
username = "@twostraws"
} else {
username = "@twostraws1"
}

// lots more complex logic


print(username)
let someCondition = false
if someCondition {
print("Do Something")
} else {
print("Got Something")
}

let scored = 85
if scored > 80 {
print("Great job")

let speed = 88
let percentage = 85

let aged = 18

if speed >= 88 {
print("Where we're going we don't need roads.")
}

if percentage < 85 {
print("Sorry, you failed the text")
}

if aged >= 18 {
print("You're eligible to vote")
}

let ourName = "Dave Lister"


let friendName = "Arnold"

if ourName < friendName {


print("It's \(ourName) vs \(friendName)")
}
if ourName > friendName {
print("It's \(friendName) vs \(ourName)")
}

var number7 = [1,2,3]

number7.append(4)

if number7.count > 2 {
number7.remove(at: 0)
}

print(number7)

let country = "Canada"


if country == "Australia" {
print("G day")
}

let nm = "Taylor Swift"


if nm != "Anonymous" {
print("Welcome, \(nm)")
}
print("the value of my name is \(nm)")

var usernamed = ""

if usernamed.isEmpty {
usernamed = "Anonymous"
}

print("Welcome, \(usernamed)!")

let age4 = 16
if age4 >= 18 {
print("You can vote in the next election")
}
if age4 <= 18 {
print("Sorry , you are too young to vote")
}

let a11 = false


let b11 = false

if a11 {
print("Code to run if a is true")
} else if b11 {
print("Code to run if b is true and a is false ")
} else {
print("Code to run if a and b are both false")
}

let temp = 25
if temp > 20 && temp < 30{
print("It's a nice day.")
}

let userAge = 04
let hasParentalConsent = false

if userAge >= 18 || hasParentalConsent || true {


print("You can buy the drink")
}

enum TransportOption {
case airplane, helicopter, bicycle, car
}

let transport = TransportOption.bicycle


let someTransport = TransportOption.car

if transport == .airplane || transport == .helicopter {


print("Let's fly !")
} else if transport == .bicycle {
print("I hope there is a bike path")
} else if transport == .car {
print("Time to get struck in traffic ")
} else {
print("I am going to hire a scooter now")
}

enum Weather {
case sun, rain, wind, snow, unknown
}

let forecast = Weather.snow

switch forecast {
case .snow:
print("It's a snowy day")
case .sun:
print("It's a sunny day ")
case .rain:
print("It's a rainy day ")
case .wind:
print("It's a windy day ")
case .unknown:
print("It is unknown")

let place = "Metropolis"

switch place {
case "Metropolis":
print("you are a batman")
case "Mega-City One":
print("You are a judge")
default:
print("Who are you?")
}

let daylight = 3
print("My true love gave to me!")

switch daylight {
case 5:
print("5 golden rings")
fallthrough
case 4:
print("4 calling birds")
fallthrough
case 3:
print("3 french hens")
fallthrough
case 2:
print("2 turtle doves")
fallthrough
default:
print("A pear tree")
}

let age2 = 18
let canVote = age2 >= 18 ? "Yes" : "No"
print(canVote)

let hour = 23
print(hour < 12 ? "It's before noon" : "midnight")

let crewCount = name.isEmpty ? "No one" : "\


(name.count) people"

enum Theme {
case light, dark
}
let theme = Theme.dark
let background = theme == .dark ? "black" : "white"
print(background)

let platform = ["iOS", "macOS", "tvOS", "watchOS"]

for os in platform {
print("Swift works great on \(os).")
}

for name in platform {


print("Swift works great on \(name).")
}

for rubberChicken in platform {


print("Swift works great on \(rubberChicken).")
}

for i in 1...5 {
print("Counting from 1 through 5: \(i)")
}

for i in 1..<5 {
print("Counting from 1 through 5: \(i)")
}

var lyric = "Haters gonna "


for _ in 1...5 {
lyric += " hate"
}

print(lyric)

var countdown = 10
while countdown > 0 {
print("\(countdown )...")
countdown -= 1
}

print("Blast off!")
let id = Int.random(in: 1...1000)
let amount = Double.random(in: 0...1)
var roll = 0
while roll != 20 {
roll = .random(in: 1...20)
print("I rolled a \(roll)")
}
print("Critical hit")

let filenames34 = ["me.jpg", "work.txt", "soap.psd",


"yours.jpg"]

for file in filenames34 {


if file.hasSuffix(".jpg") == false {
continue
}
print("Found picture: \(file)")
}

//print(multiples)

//let number1 = 3
//let number2 = 5
//
//for i in 1...100 {
// if i.isMultiple(of: 3) && i.isMultiple(of: 5) {
// print("The number \(i) is ------ fizzbuzz")
// }
// else if i.isMultiple(of: 5){
// print("The number \(i) is ------ buzz")
// }
// else if i.isMultiple(of: 3) {
// print("The number \(i) is ------ fizz")
// }
// else {
// print("The number \(i) is ------ \(i)")
// }
//}

func doMath() -> Int {


return 5 + 5
}

func doMoreMath() -> Int {


5+5
}

doMath()
doMoreMath()

func greet(name: String) -> String {


if name == "Taylor Swift" {
return "oh wow"
} else {
return "Hello, \(name)"
}
}

greet(name: "Kumar ")


greet(name: "Taylor Swift")

func greeter(name: String) -> String {


name == "Taylor Swift" ? "oh wow" : "Hello, \
(name)"

greeter(name: "Kumar")
greeter(name: "Taylor Swift")

func getUser8() -> (first: String , last: String) {


return (first: "Taylor", last: "Swift")
}

let user7 = getUser8()


user7.first
user7.last

func setAge(_ person: String, to value: Int) {


print("\(person) is no \(value)")
}

setAge("Me", to: 100)

func findDirections(_ from: String, to alpha: String,


route: String = "fastest", avoidHighways:Bool = false) {
print("the value is \(from)" )
print("the value is \(alpha)")
}

findDirections("Me", to: "Her")

func getUser12() -> (first: String, last: String) {


(first: "taylor", last: "swift")
}

let user12 = getUser12()


print(user12.first)

func setReactorStatus(primaryActive: Bool, hack: Bool,


hackNot: Bool) {

setReactorStatus(primaryActive: true, hack: false,


hackNot: false)

func setAge(for person: String, to value: Int) {


print("\(person) is now \(value)")
}

setAge(for: "Paur", to: 40)

func setAge13(_ robot: String , to value: Int) {


print("\(robot) is now \(value)")
}

setAge13("robot", to: 30)

//open("photo.jpg", "recipes.txt")

func +(leftNumber: inout Int, rightNumber: inout Int) ->


Int {
// code here
return leftNumber * rightNumber
}

func doubleInPlace(number: inout Int) {


number *= 2
}

var myNum = 10
doubleInPlace(number: &myNum)
//let some3 = doubleInPlace(number: &23)

// block of code called closure

func pay(user: String, amount: Int) {


// code
}

let payment = { (user: String, amount: Int) in


// code
}

func pay1(user: String, amount : Int) {


// code
}

let payment1 = {(user: String, amount: Int) in


// code
}

//let payment34 = { (user: String) -> Bool in


// print("Paying \(user)...")
// return true
//
//}

let payment34 = { () -> Bool in


//print("Paying \(user)...")
return false

}
payment34()

func animate(duration: Double, animations: () -> Void)


{
print("Starting a \(duration) second animations...")
animations()
}

animate(duration: 3) {
print("Fade out the image")
}

let changeSpeed = { (_ speed: Int) in


print("Changing speed to \(speed) kph")
}

changeSpeed(34)

func buildCar(name: String, engine: (Int) -> Void) {


// build the car
engine(5)

buildCar(name: "MyCar", engine: changeSpeed)


buildCar(name: "Some Car") { x in
print("now it runs in \(x) mph")
}

func reduce(_ values: [Int], using closure: (Int, Int) ->


Int) -> Int {
var current = values[0]
for value in values[1...] {
current = closure(current, value)
}

return current
}

let numbers4 = [10,20,30]


let sum1 = reduce(numbers4) { runningTotal, next in
runningTotal + next
}

print(sum1)

let multiplied = reduce(numbers4) { $0 * $1 }


print(multiplied)

let sum = reduce(numbers4, using: %)


print(sum)

// returning closures from functions


//func nada(some: String) -> ((String) -> Int) {
// let some: ((String) -> Int)
// return some
//}

print(Int.random(in: 1...10))

func getRandomNumber() -> Int {


Int.random(in: 1...10)
}

print(getRandomNumber())

func makeRandomGenerator() -> () -> Int {


let function = { Int.random(in: 1...10)

}
return function
}

let generator = makeRandomGenerator()


let random1 = generator()
print(random1)

//print(makeRandomGenerator())

func makeRandomNumberGenerator() -> () -> Int {


return {
var previousNumber = 0
var newNumber: Int

repeat {
newNumber = Int.random(in: 1...10)
} while newNumber == previousNumber
previousNumber = newNumber
return newNumber

}
}

let generator1 = makeRandomNumberGenerator()


for _ in 1...10 {
print(generator1())
}

// struct and tuple

struct Users5 {
var name: String
var age: Int
var city: String
}

let user1 = Users5(name: "Kumar ", age: 23, city:


"Katras")
print(user1.name)
// property observer
// willset and didset

print("string".count)
print("string".hasPrefix("Hello"))
print("string".uppercased())
print("string".sorted())

struct Abuser {
var name: String
var yearsActive = 0
}

struct Employer {
var name: String
var yearsActive = 0

extension Employer {
init() {
self.name = "Anonymous"
print("Creating an anonymous employee")
}
}

let roslin = Employer(name: "Roslin")


let adama = Employer(name: "Adama", yearsActive:
45)

let dama = Employer()


print(dama.name)

struct Student {
var name: String
var bestFriend: String

init(name: String, bestFriend: String) {


print("Enrolling \(name) in class...")
self.name = "Hi" + name
self.bestFriend = bestFriend
}
}

// lazy

struct Unwrap {
static let appURL = "https://itunes.apple.com"
}

//Unwrap.appURL
struct SomeStruct {
private static var entropy = Int.random(in: 1...10)
static func getEntropy() -> Int {
entropy += 1
return entropy
}
}

//print(SomeStruct.entropy)
print(SomeStruct.getEntropy())

private var item = ""


// override

//var message1 = "Welcome"


//var greeting1 = message1
//greeting1 = "hello"
//message1

// Day 12
protocol Purchaseable {
var name: String {get set }
// var price: Int { get set }
}

extension Purchaseable {
func buy(_ item: Purchaseable) {
print("I'm buying \(item.name)")
}
}

protocol Product {
var price: Double { get set }
var weight: Int { get set }
}
protocol Computer: Product {

var cpu: String { get set }


var memory: Int { get set }
var storage: Int { get set }
}

protocol Laptop: Computer {

var screenSize: Int { get set }


}

struct Asus: Laptop {


var screenSize: Int
var cpu: String
var memory: Int
var storage: Int
var price: Double
var weight: Int
}

let asu = Asus(screenSize: 23, cpu: "23", memory: 23,


storage: 23, price: 23.0, weight: 23)

let numbers23 = [4,8,16]


let allEven = numbers23.allSatisfy { $0.isMultiple(of: 4)
}
print(allEven)

let number34 = Set([4,8,15,16])


//let allEven23 = number34.allSatisfy { $0.isMultiple(of:
4)}
let allEven23 = number34.allSatisfy { $0.isMultiple(of:
4) }

let number47 = ["four": 4, "eight": 8, "fifth" : 5]


let allEven3 = number47.allSatisfy
{ $0.value.isMultiple(of: 4) }

enum num: CaseIterable {


case one
case two
case three
case four
case five
case six
case seven
case eight
case nine
case zero

static func random() -> num {


num.allCases.randomElement()!
}
}

let myNums = [num.one : "A",


num.two: "B",
num.three: "C",
num.four: "D",
num.five: "E",
num.six: "S",
num.seven: "G",
num.eight: "H",
num.nine: "N",
num.zero: "O"]

myNums[num.two]
num.random()

// have faith

func getUserName() -> String? {


"Taylor"
}

if let username = getUserName() {


print("Username is \(username)")
} else {
print("No username")
}

func getMeaningOfLife() -> Int? {


42
}

func printMeaningOfLife() {
if let name = getMeaningOfLife() {
print(name)
}
}

func printMeaningOfLife1() {
guard let name = getMeaningOfLife() else {
print(name)
return
}
print(name)
}

//let savedData = loadSavedMessage() ?? ""


// let savedData = first() ?? second() ?? ""

let names = ["Kumar": "greater", "Utsav" : "haha",


"musibat" : "majak"]
let surname1 = names["Kumar"]?.first?.uppercased()
surname1

func runRiskyFunction() throws -> Int {


// print something
43
}

do {
let result = try runRiskyFunction()
print(result)
} catch {
// it failed
}

if let result = try? runRiskyFunction() {


print(result)
}

// failable init
// init?() init()

struct Employee {
var username: String
var password: String

init?(username: String, password: String ) {


guard password.count >= 8 else { return nil }
guard password.lowercased() != "Password"
else { return nil }

self.username = username
self.password = password

}
}

let tim = Employee(username: "2323", password:


"232")
let cook = Employee(username: "sfsfsfdsfdsfsfs",
password: "lsjjljlkjljlkj")
tim?.username
cook?.password
// type casting useful in swift

class MyClass {
let property1: String = ""
}

class SubClass: MyClass {


let property2: String = "asdf"

let object = SubClass()

func takes(myClass: MyClass) -> MyClass {


return myClass
}

let modifiedObject = takes(myClass: object)

takes(myClass: object )
print(modifiedObject.property1)
print((modifiedObject as! SubClass).property2)

You might also like