Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Session11

import Foundation
import Glibc

/*
enum mobile {
    case iPhone
    case andriod
}
var userDevice: mobile = mobile.andriod
print(userDevice)
userDevice = .iPhone

if userDevice == .iPhone {
    print("this is andriod")
}

enum mobile2 {
    case iPhone(String)
    case andriod(String)
}
var userDevice2: mobile2 = .andriod("Galaxy")
print(userDevice2)

switch  userDevice2 {
    case .andriod(let model) :
         print(model)
    case .iPhone(let model) :
         print(model)
    default :
         print("No")
}


enum paymentMethod {
    case chash
    case visa
    case master(String)
}

var payment: paymentMethod = .master("depit")
payment = .chash
switch payment {
    case .master(let type):
    print("You will pay by master \(type)")
    case .chash:
    print("You will pay by chash")
    case .visa:
    print("You will pay by visa")
    
    default :
    print("No")
}
*/

enum paymentMethod: Int {
    case visa 
    case chash = 3
    case master  
}

print(paymentMethod.master.rawValue)

enum months: Int {
    case january = 1
    case february
    case march
    case april
}
print(months.january.rawValue)







Compile and Execute Swift Online

import UIKit

// closures -> function without name
                // parameter     return type
let myClosure : (_ x:Int,_ y:Int) -> Int = {
     (x,y) in return x*y
}

print(myClosure(10,10))

let clousure:(_ n:Int,_ n1:Int) -> Int = {
    $0 * $1  // we not need to use return swift
}

// clousers may be optional
let myClosure1 : ((_ x:Int,_ y:Int) -> Int)? = {

    $0*$1
}

if let closure = myClosure1{
    print(closure(10,100))
}

myClosure1?(10,10) // if not nil the (10,10) execute

// closure can use as aparameter in function

func makeRequest(authenticated: @autoclosure ()->Bool){ // @autoclousure make { } by default
    if authenticated(){
        print("request suceesfully")
    }else {
        print("please sign in first")
    }
}
makeRequest(authenticated: true ) // or{true} but @autoclosure make {}
makeRequest(authenticated: false)

func make_request(name:String ,  authenticate1:()->Bool){
    if authenticate1(){
        print("Requesting --- ")
    }else{
        print("please sign in first")
    }
}

make_request(name: "mahmoud" ){true} // if the closure the last parameter in function
                                     // we can use this synax while calling function
makeRequest(authenticated: true)

Session10

import Foundation
import Glibc









exersice 13.01 Closers (Wallet Sort)

import Foundation
import Glibc

// Функция принимает функцию и возвращает массив [Int].
// Входная функция принимает Int и возвращает Bool.
// Принимает массив кошелька и функцию в названии которой указано какие купюры 
// нужно отфильтровать.

func handle(wallet: [Int], closure: (Int) -> Bool) -> [Int] {
    var returnWallet : [Int] = []
    for banknot in wallet {
        if closure(banknot) {
            returnWallet.append(banknot)
        }
    }
    return returnWallet
}

// 1) Вариант с созданием отдельных функицй для каждого фильтра
func compare100(banknot: Int) -> Bool {
    return banknot == 100
}

func compare1000(banknot: Int) -> Bool {
    return banknot == 1000
}

var wallet = [10, 50, 100, 100, 5000, 100, 50, 50, 1000, 100, 500]
print(handle(wallet: wallet, closure: compare100))
print(handle(wallet: wallet, closure: compare1000))

// 2) Вариант с замыкающим выражением
let a = handle(wallet: wallet, closure: {(banknot: Int) -> Bool in
    return banknot >= 1000
})
print(a)

// 3) Укороченный вариант с замыкающим выражением
let b = handle(wallet: wallet, closure: {banknot in
    return banknot == 100
})
print(b)

// 4) Ещё более укороченный вариант с замыкающим выражением
let c = handle(wallet: wallet, closure: {banknot in banknot <= 50})
print(c)

// 4) Ещё более укороченный вариант с замыкающим выражением c использованием 
// сокращённых имён доступа
let d = handle(wallet: wallet, closure: {$0 <= 10})
print(d)

// 5) Если входной параметр-функция последний, его можно вынести за скобки
let e = handle(wallet: wallet) {$0 == 500}
print(e)

// Вариант с более сложным фильтром (ищем только 10ки и 50ки)
let successBanknotes = [10, 50]
let f = handle(wallet: wallet)
{banknot in
    for number in successBanknotes {
        if number == banknot {
            return true
        }
    }
    return false
}
print(f)

exersice 12.02 Functions Types (Book)

import Foundation
import Glibc

func printText() -> (String) {
    return "Очень хорошая книга"
}
func returnPrintTextFunction() -> () -> String {
    return printText
}
let newFunctionInLet = returnPrintTextFunction()
print(newFunctionInLet())

exercise 12.01 Functions (Wallet)

import Foundation
import Glibc
 
func generateWallet(walletLenght: Int) -> [Int] {
    let typesOfBanknotes = [50, 100, 500, 1000, 5000]
    var wallet: [Int] = []
    for _ in 1...walletLenght {
        let randomIndex = 2
        wallet.append(typesOfBanknotes[randomIndex])
    }
    return wallet
}
func sumWallet(banknotsFunction wallet: (Int) -> ([Int]) ) -> Int? {
    let myWalletArray = wallet(5)
    var sum: Int = 0
    for oneBanknote in myWalletArray {
        sum += oneBanknote
    }
    return sum
}
print(sumWallet(banknotsFunction: generateWallet)!)

exercise 11.2 Cycle for (Chess)

import Foundation
import Glibc
 
typealias Chessman = [String:(alpha:Character,num:Int)?]
var Chessmans: Chessman = ["White King":("C",6), "Black Rook":("E",2), "Black Bishop":nil]

// проверяем, существуют ли фигура
for (name, coordinates) in Chessmans {
    if let checkCoordinates = coordinates {
        print("Coordinates of \(name) is \(checkCoordinates)")
    }else{
        print("\(name) id dead")
    }
}

square rooter

var a = 0
while (a <= 100) {
print(a, terminator:", ")
a+=1
}

exercise 11.1 Cycle for (Students marks)

import Foundation
import Glibc
 
var students : [String:[String:UInt]] = ["Kirill":["3th of november": 1, "21st of september": 4], 
"Dasha":["13th of september": 4, "3th of november": 3], 
"Nikita": ["24th of october": 2, "13th of september": 3]]
var studentsAvagrages : Float = 0
for (name, dateAndMark) in students {
    var studentAvarage : Float = 0
    var sumOfAllMarks : UInt = 0
    for (_, mark) in dateAndMark{
        sumOfAllMarks += mark
    }
    studentAvarage = Float(sumOfAllMarks) / Float(dateAndMark.count)
    print("Avarage mark for student \(name) is \(studentAvarage)")
    studentsAvagrages += studentAvarage
}
studentsAvagrages = studentsAvagrages / Float(students.count)
print("Avarage mark of all students is \(studentsAvagrages)")

exercise 10 Dictionares

import Foundation
import Glibc

typealias Chessman = [String:(alpha:Character,num:Int)?]
var Chessmans: Chessman = ["White King":("C",6), "Black Rook":("E",2), "Black Bishop":nil]

// проверяем, существуют ли первая фигура
if let coordinates = Chessmans["White King"]! {
    print("Coordinates of White King is \(coordinates)")
}else{
    print("White King id dead")
}
// проверяем, существуют ли вторая фигура
if let coordinates = Chessmans["Black Rook"]! {
    print("Coordinates of Black Rook is \(coordinates)")
}else{
    print("Black Rook id dead")
}
// проверяем, существуют ли третья фигура
if let coordinates = Chessmans["Black Bishop"]! {
    print("Coordinates of Black Bishop is \(coordinates)")
}else{
    print("Black Bishop id dead")
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.